next up previous contents
Next: Dealing with Multiple Exceptions Up: Exceptions Previous: Introduction   Contents

Tracebacks

Whenever you use a try/except clause, the programming statements contained in the try portion of the code are executed in a ``protected'' environment, in the sense that errors occurring in that code will not cause python to terminate. Instead, you have the opportunity to catch and examine the error, and take the action of your choice. Perhaps the most classic example of the try/except clause is to catch problems when you attempt to open a file. Let's take a look at what happens when we try to open a file that doesn't exist:
>>> f = open('not.a.file')
Traceback (innermost last):
  File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'not.a.file'
The traceback provided by Python contains useful information. First, the line and file in which the error was encountered is displayed. While this is not of much use in an interactive session, it is invaluable when running your Python programs from a file. The final line of the traceback is especially important when considering how to deal with problems that might arise in your program, since it gives the name of the exception which was encountered. Many exceptions also provide specific information about the nature of the exception, like the ``No such file or directory'' message in this example. You can capture this additional information in a variable by specifying the name of that variable after the name of the exception you're catching, separated by a comma.

>>> try:
...     f = open('not.a.file')
... except IOError,msg:
...     print msg
... 
[Errno 2] No such file or directory: 'not.a.file'
If Python encountered this code in a program it was executing, the program would not terminate after failing to open the file, since the IOError was trapped. In many situations, you'll want to terminate your program when you encounter an exception, by calling the exit function of the sys module (See Section 8.8 for details.)


next up previous contents
Next: Dealing with Multiple Exceptions Up: Exceptions Previous: Introduction   Contents
Phil Spector 2003-11-12