O'Reilly logo

Python in a Nutshell by Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. Exceptions

Python uses exceptions to communicate errors and anomalies. An exception is an object that indicates an error or anomalous condition. When Python detects an error, it raises an exception; that is, it signals the occurrence of an anomalous condition by passing an exception object to the exception-propagation mechanism. Your code can also explicitly raise an exception by executing a raise statement.

Handling an exception means receiving the exception object from the propagation mechanism and performing whatever actions are needed to deal with the anomalous situation. If a program does not handle an exception, it terminates with an error traceback message. However, a program can handle exceptions and keep running despite errors or other abnormal conditions.

Python also uses exceptions to indicate some special situations that are not errors, and are not even abnormal occurrences. For example, as covered in Chapter 4, an iterator’s next method raises the exception StopIteration when the iterator has no more items. This is not an error, and it is not even an anomalous condition, since most iterators run out of items eventually.

The try Statement

The try statement provides Python’s exception-handling mechanism. It is a compound statement that can take one of two different forms:

  • A try clause followed by one or more except clauses

  • A try clause followed by exactly one finally clause

try/except

Here’s the syntax for the try/except form of the try statement:

try:
    statement(s) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required