Glossary

Exception

An exception is an object that Python creates when an error or unusual condition occurs during program execution. Exceptions disrupt the normal flow of control: when one is raised, Python unwinds the call stack looking for an exception handler (a try /except block) that can handle it. If no handler is found, the program terminates with a traceback.

Python has a rich hierarchy of built-in exceptions. At the top is BaseException, from which Exception inherits. Common exceptions include ValueError (wrong value), TypeError (wrong type), KeyError (missing dictionary key), IndexError (index out of range), AttributeError (missing attribute), FileNotFoundError, ZeroDivisionError, and ImportError. You should catch Exception (not BaseException) as a broad catch-all, since BaseException includes SystemExit, KeyboardInterrupt, and GeneratorExit.

You raise exceptions with the raise statement: raise ValueError("invalid input"). Custom exception classes should inherit from Exception or one of its subclasses. Exceptions carry useful information: the message, the traceback (accessible via the __traceback__ attribute), and optionally chained exceptions (using raise X from Y). The ability to define, raise, catch, and chain exceptions is fundamental to writing robust Python code.

Related terms: Try/Except, EAFP, Context Manager

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.