Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outdated book description of Try-Except-Finally statement

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.

like image 227
bdhar Avatar asked Sep 23 '11 05:09

bdhar


3 Answers

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

like image 89
Andrew Walker Avatar answered Nov 04 '22 12:11

Andrew Walker


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'
like image 41
Tehnix Avatar answered Nov 04 '22 10:11

Tehnix


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

like image 1
Blender Avatar answered Nov 04 '22 10:11

Blender