16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

168 CHAPTER 8 ■ EXCEPTIONS<br />

Invalid input: name 'foo' is not defined<br />

Please try again<br />

Enter the first number: 10<br />

Enter the second number: 2<br />

x/y is 5<br />

And Finally . . .<br />

Finally, there is the finally clause. You use it <strong>to</strong> do housekeeping after a possible exception. It<br />

is combined with a try clause (but not an except clause):<br />

x = None<br />

try:<br />

x = 1/0<br />

finally:<br />

print 'Cleaning up...'<br />

del x<br />

In the preceding, you are guaranteed that the finally clause will get executed, no matter<br />

what exceptions occur in the try clause. (The reason for initializing x before the try clause is<br />

that otherwise it would never get assigned a value because of the ZeroDivisionError. This would<br />

lead <strong>to</strong> an exception when using del on it within the finally clause, which you wouldn’t catch.)<br />

If you run this, the cleanup comes before the program crashes and burns:<br />

Cleaning up...<br />

Traceback (most recent call last):<br />

File "C:\python\div.py", line 4, in ?<br />

x = 1/0<br />

ZeroDivisionError: integer division or modulo by zero<br />

Exceptions and Functions<br />

Exceptions and functions work <strong>to</strong>gether quite naturally. If an exception is raised inside a function,<br />

and isn’t handled there, it propagates (bubbles up) <strong>to</strong> the place where the function was called.<br />

If it isn’t handled there either, it continues propagating until it reaches the main program (the<br />

global scope), and if there is no exception handler there, the program halts with an error message<br />

and some information about what went wrong (a stack trace). Let’s take a look at an example:<br />

>>> def faulty():<br />

... raise Exception('Something is wrong')<br />

...<br />

>>> def ignore_exception():<br />

... faulty()<br />

...

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!