On this link (https://docs.python.org/2/tutorial/errors.html#defining-clean-up-actions) following is said:
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.
CODE 1:
try:
print "Performing an action which may throw an exception."
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
finally:
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
OUTPUT 1:
Performing an action which may throw an exception.
Everything looks great!
Finally is called directly after executing the try statement whether an exception is thrown or not.
CODE 2:
try:
print "Performing an action which may throw an exception."
raise Exception('spam', 'eggs') # This is new
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
finally:
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
OUTPUT 2:
Performing an action which may throw an exception.
An exception was thrown!
('spam', 'eggs')
Finally is called directly after executing the try statement whether an exception is thrown or not.
What I get from this is that else
is executed only when there is no exception.
QUESTION:
Is finally
used just for better readability ?
Because I can just put this print statement after try, like in this code.
CODE 3:
try:
print "Performing an action which may throw an exception."
#raise Exception('spam', 'eggs') # with this line or without last print is done
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
print "Finally is called directly after executing the try statement whether an exception is thrown or not."