Linux/Unix > Python Essential Reference, Second Edition > 1. A Tutorial Introduction > Exceptions | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104026065049168166116064

### Exceptions

If an error occurs in your program, an exception is raised and an error message such as the following appears:

    Traceback (most recent call last):
     File "<interactive input>", line 42, in foo.py
    NameError: a

The error message indicates the type of error that occurred, along with its location. Normally, errors cause a program to abort. However, you can catch and handle exceptions using the `try` and `except` statements, like this:

    try:
        f = open("file.txt","r")
    except IOError, e:
        print e

If an `IOError` occurs, details concerning the cause of the error are placed in `e` and control passes to the code in the `except` block. If some other kind of exception is raised, it’s passed to the enclosing code block (if any). If no errors occur, the code in the `except` block is ignored.

The `raise` statement is used to signal an exception. When raising an exception, you can use one of the built-in exceptions, like this:

    raise RuntimeError, "Unrecoverable error"

Or you can create your own exceptions, as described in the section “Defining New Exceptions” in Chapter 5, “Control Flow.”

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.