O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Exception Handling

When errors occur, Python throws an exception and prints an informative traceback to standard output. If the error occurred in a source file and not a console session, you get the filename and line number. Here’s a simple error, nested three functions deep, and its traceback:

>>> def func1(arg):
...     func2(arg)
...     
>>> def func2(arg):
...     func3(arg)
...     
>>> def func3(arg):
...     # this should cause an error
...     return arg / 0
...     
>>> func1(17)
Traceback (innermost last):
  File "<interactive input>", line 0, in ?
  File "<interactive input>", line 2, in func1
  File "<interactive input>", line 2, in func2
  File "<interactive input>", line 3, in func3
ZeroDivisionError: integer division or modulo
>>>

The traceback tells us where the error happened and the enclosing functions that called the functions that caused the error.

Exceptions can be handled using the try ...except and try ...finally structure. If you aren’t used to exception handling, these offer two benefits over Visual Basic-style error-handling. First, you can write a decent-sized chunk of code and put the error handlers at the end; the intent of the programmer is clearer than with a lot of on error goto and on error resume next statements. Second, exception handlers don’t work on just the present chunk of code, but also on any subroutines within it, however deeply nested.

The except clause can optionally specify particular error types to look for or handle all errors:

>>> try: ... y_scale_factor = plotHeight / (dataMax ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required