Deprecated Try-Except-finally statement book description

I follow the Apress, Beginning Python from Novice to Professional book. It is mentioned that:

eventually. You can use try / finally if you need to make sure that some code (such as cleanup code) is executed regardless of whether an exception is raised or not. This code is then placed at the end of the paragraph. Note that you cannot have both except sentences and, finally, in the same try statement, but you can put it 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 conclusion

 Yesss integer division or modulo by zero Cleanup 

Here I used except and finally in the same try segment, right? And the code is working fine as expected. I can’t understand what the book says!

Someone, please specify. Thanks.

+8
python exception
source share
4 answers

This has been fixed since python 2.5 and is clearly stated in the documentation

In other words, your book is incorrect / out of date

+14
source share

I believe that the book really sets an example myself, so I don’t know what he meant by that. As noted in the previous answer, this was changed in python 2.5, so that

 try: try: print 'something' except: print 'some weird error' finally: print 'finally something 

Is equivalent

 try: print 'something' except: print 'some weird error' finally: print 'finally' 
+6
source share

This book may be wrong, I'm afraid, because the Python documentation uses all three. Maybe it's time to get a new book?

+1
source share

Prior to python 2.4, it was not possible to finally merge with the except or else statement. But since python 2.5, like other object-oriented programming languages, it supports union except for blocks and finally block. Check out the latest python documentation.

0
source share

All Articles