When I write code in Python with exception handling I can write code like:
try:
some_code_that_can_cause_an_exception()
except:
some_code_to_handle_exceptions()
else:
code_that_needs_to_run_when_there_are_no_exceptions()
How does this differ from:
try:
some_code_that_can_cause_an_exception()
except:
some_code_to_handle_exceptions()
code_that_needs_to_run_when_there_are_no_exceptions()
In both cases code_that_needs_to_run_when_there_are_no_exceptions()
will execute when there are no exceptions. What's the difference?
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\n"
if __name__ == "__main__":
print "Example 1\n"
try:
throws_ex()
except Exception, e:
# Handle it
print "Handling Exception\n"
else:
print "No Exceptions\n"
do_more()
print "example 2\n"
try:
throws_ex()
except Exception, e:
print "Handling Exception\n"
do_more()
print "example 3\n"
try:
throws_ex(False)
except Exception, e:
print "Handling Exception\n"
else:
do_more()
print "example 4\n"
try:
throws_ex(False)
except Exception, e:
print "Handling Exception\n"
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!
Actually, in the second snippet, the last line executes always.
You probably meant
try:
some_code_that_can_cause_an_exception()
code_that_needs_to_run_when_there_are_no_exceptions()
except:
some_code_to_handle_exceptions()
I believe you can use the You use the else
version if it makes the code more readable.else
variant if you don't want to catch exceptions from code_that_needs_to_run_when_there_are_no_exceptions
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With