Outdated book description of Try-Except-Finally statement
Asked Answered
K

4

8

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.

Karenkarena answered 23/9, 2011 at 5:37 Comment(2)
As the accepted answer says, your book is out of date. In fact it is more than 5 years out of date. There is a lot that has changed in Python over the last 5 years. Do yourself a favour and buy a more recent book.Baikal
Throw all your books out and work directly from the documentation. In particular, note the version of Python for which any book/documentation applies. Be sure to skim the whatsnew list, in particular every major 2.x or 3.x version (although 2.x has now stabilized on 2.7 so this is historical).Fan
A
14

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

Alteration answered 23/9, 2011 at 5:41 Comment(0)
O
6

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'
Opprobrium answered 23/9, 2011 at 5:45 Comment(0)
C
1

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

Cantina answered 23/9, 2011 at 5:42 Comment(0)
G
0

Until python 2.4 it was not allowed to combine finally with except or else statement. But since python 2.5, like other object oriented programming language it support the combining except blocks and a finally block. Refer the latest python documentation

Gwen answered 23/5, 2015 at 19:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.