In the second example, code_that_needs_to_run_when_there_are_no_exceptions()
will be ran when you do have an exception and then you handle it, continuing after the except.
so ...
In both cases code_that_needs_to_run_when_there_are_no_exceptions() will execute when there are no exceptions, but in the latter will execute when there are and are not exceptions.
Try this on your CLI
#!/usr/bin/python
def throws_ex( raise_it=True ):
if raise_it:
raise Exception("Handle me")
def do_more():
print "doing more
"
if __name__ == "__main__":
print "Example 1
"
try:
throws_ex()
except Exception, e:
# Handle it
print "Handling Exception
"
else:
print "No Exceptions
"
do_more()
print "example 2
"
try:
throws_ex()
except Exception, e:
print "Handling Exception
"
do_more()
print "example 3
"
try:
throws_ex(False)
except Exception, e:
print "Handling Exception
"
else:
do_more()
print "example 4
"
try:
throws_ex(False)
except Exception, e:
print "Handling Exception
"
do_more()
It will output
Example 1
Handling Exception
example 2
Handling Exception
doing more
example 3
doing more
example 4
doing more
You get the idea, play around with exceptions, bubbling and other things! Crack out the command-line and VIM!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…