Just curious, why does the following code
import sys
class F(Exception):
sys.stderr.write('Inside exception\n')
sys.stderr.flush()
pass
sys.stderr.write('Before Exception\n')
sys.stderr.flush()
try:
raise F
except F:
pass
output:
Inside exception
Before Exception
and not:
Before exception
Inside Exception
As Sven rightly said, class bodies are executed immediately when the class definition is executed.
In your code, your definition of your class F is above this command
sys.stderr.write('Before Exception\n')and hence thissys.stderr.write('Inside exception\n')gets executed first and consequently its output is seen first.As a test, run this program –
The output now you will get is –
This is simply because the statement
sys.stderr.write('Before Exception\n')gets executed before the class definition gets executed.Infact, the printing of
Inside Exceptionhas nothing to do with your initializing an instance of F (by usingraise). It will get printed no matter you initialize an instance of F or not.Try this –
Still you will get this output –
although you have not made an instance of the class F.