Linux/Unix > Python Essential Reference, Second Edition > 5. Control Flow > Exceptions | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104031089146158228043172

### Exceptions

Exceptions indicate errors and break out of the normal control flow of a program. An exception is raised using the `raise` statement. The general format of the `raise` statement is `raise` `exception` `[,` `value` `]` where `exception` is the exception type and `value` is an optional value giving specific details about the exception. For example:

    raise RuntimeError, 'Unrecoverable Error'

If the `raise` statement is used without any arguments, the last exception generated is raised again (although this works only while handling a previously raised exception).

To catch an exception, use the `try` and `except` statements, as shown here:

    try:
        f = open('foo')
    except IOError, e:
        print "Unable to open 'foo': ", e

When an exception occurs, the interpreter stops executing statements in the `try` block and looks for an `except` clause that matches the exception that has occurred. If found, control is passed to the first statement in the `except` clause. Otherwise, the exception is propagated up to the block of code in which the `try` statement appeared. This code may itself be enclosed in a `try-except` that can handle the exception. If an exception works its way up to the top level of a program without being caught, the interpreter aborts with an error message. If desired, uncaught exceptions can also be passed to a user-defined function `sys.excepthook()` as described in Appendix A, “The Python Library,” `sys` module.

The optional second argument to the `except` statement is the name of a variable in which the argument supplied to the `raise` statement is placed if an exception occurs. Exception handlers can examine this value to find out more about the cause of the exception.

Multiple exception-handling blocks are specified using multiple `except` clauses, such as in the following example:

    try:
       do something
    except IOError, e:
       # Handle I/O error
       ...
    except TypeError, e:
       # Handle Type error
       ...
    except NameError, e:
       # Handle Name error
       ...

A single handler can catch multiple exception types like this:

    try:
       do something
    except (IOError, TypeError, NameError), e:
       # Handle I/O, Type, or Name errors
       ...

To ignore an exception, use the `pass` statement as follows:

    try:
       do something
    except IOError:
       pass              # Do nothing (oh well).

To catch all exceptions, omit the exception name and value:

    try:
       do something
    except:
       print 'An error occurred'

##### Table 5.1. Built-in Exceptions

Exception | Description
--- | ---
`Exception` | The root of all exceptions
`SystemExit` | Generated by `sys.exit()`
`StandardError` | Base for all built-in exceptions
`ArithmeticError` | Base for arithmetic exceptions
`FloatingPointError` | Failure of a floating-point operation
`OverflowError` | Arithmetic overflow
`ZeroDivisionError` | Division or modulus operation with 0
`AssertionError` | Raised by the `assert` statement
`AttributeError` | Raised when an attribute name is invalid
`EnvironmentError` | Errors that occur externally to Python
`IOError` | I/O or file-related error
`OSError` | Operating system error
`WindowsError` | Error in Windows
`EOFError` | Raised when the end of the file is reached
`ImportError` | Failure of the `import` statement
`KeyboardInterrupt` | Generated by the interrupt key (usually Ctrl+C)
`LookupError` | Indexing and key errors
`IndexError` | Out-of-range sequence offset
`KeyError` | Nonexistent dictionary key
`MemoryError` | Out of memory
`NameError` | Failure to find a local or global name
`UnboundLocalError` | Unbound local variable
`RuntimeError` | A generic catch-all error
`NotImplementedError` | Unimplemented feature
`SyntaxError` | Parsing error
`TabError` | Inconsistent tab usage (generated with `-tt` option)
`IndentationError` | Indentation error
`SystemError` | Nonfatal system error in the interpreter
`TypeError` | Passing an inappropriate type to an operation
`ValueError` | Inappropriate or missing value
`UnicodeError` | Unicode encoding error

The `try` statement also supports an `else` clause, which must follow the last `except` clause. This code is executed if the code in the `try` block doesn’t raise an exception. Here’s an example:

    try:
       f = open('foo', 'r')
    except IOError:
       print 'Unable to open foo'
    else:
       data = f.read()
       f.close()

The `finally` statement defines a cleanup action for code contained in a `try` block. For example:

    f = open('foo','r')
    try:
       # Do some stuff
       ...
    finally:
       f.close()
       print "File closed regardless of what happened."

The `finally` clause isn’t used to catch errors. Rather, it’s used to provide code that must always be executed, regardless of whether an error occurs. If no exception is raised, the code in the `finally` clause is executed immediately after the code in the `try` block. If an exception occurs, control is first passed to the first statement of the `finally` clause. After this code has executed, the exception is re-raised to be caught by another exception handler. The `finally` and `except` statements cannot appear together within a single `try` statement.

Python defines the built-in exceptions listed in Table 5.1. (For specific details about these exceptions, see Appendix A.)

All the exceptions in a particular group can be caught by specifying the group name in an `except` clause. For example,

    try:
         statements
    except LookupError:     # Catch IndexError or KeyError
         statements

or

    try:
         statements
    except StandardError:   # Catch any built-in exception
         statements

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