Next: Expressions and conditions Up: Execution model Previous: Code blocksexecution

Exceptions

Exceptions are a means of breaking out of the normal flow of control of a code block in order to handle errors or other exceptional conditions. An exception is raised at the point where the error is detected; it may be handled by the surrounding code block or by any code block that directly or indirectly invoked the code block where the error occurred.

The Python interpreter raises an exception when it detects an run-time error (such as division by zero). A Python program can also explicitly raise an exception with the raise statement. Exception handlers are specified with the try...except statement.

Python uses the ``termination'' model of error handling: an exception handler can find out what happened and continue execution at an outer level, but it cannot repair the cause of the error and retry the failing operation (except by re-entering the the offending piece of code from the top).

When an exception is not handled at all, the interpreter terminates execution of the program, or returns to its interactive main loop.

Exceptions are identified by string objects. Two different string objects with the same value identify different exceptions.

When an exception is raised, an object (maybe None) is passed as the exception's ``parameter''; this object does not affect the selection of an exception handler, but is passed to the selected exception handler as additional information.

See also the description of the try and raise statements.


guido@cwi.nl