>>> 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.)