I am following Apress, Beginning Python from Novice to Professional
book. It is mentioned that:
finally. You can use try/finally if you need to make sure that some code (for example, cleanup code) is executed regardless of whether an exception is raised or not. This code is then put in the finally clause. Note that you cannot have both except clauses and a finally clause in the same try statement—but you can put one inside the other.
I tried this code:
def someFunction():
a = None
try:
a = 1 / 0
except ZeroDivisionError, e:
print 'Yesss'
print e
finally:
print 'Cleanup'
del a
if __name__ == '__main__':
someFunction()
...and the output is
Yesss
integer division or modulo by zero
Cleanup
Here, I have used except
and finally
in the same try
segment, haven't I? And the code works fine as expected. I can't quite get what the book says!
Someone please clarify. Thanks.
This has been fixed since python 2.5, and is clearly noted in the documentation
In other words, your book is incorrect / out of date
I believe the book actually gives the example itself, hence I don't know what he meant by it exactly. As the previous answer noted, this was changed in python 2.5 so that
try:
try:
print 'something'
except:
print 'some weird error'
finally:
print 'finally something
Is equivalent to
try:
print 'something'
except:
print 'some weird error'
finally:
print 'finally'
That book might be wrong, I'm afraid, as the Python documentation uses all three. Maybe it's time to get a new book?
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