Built-in Exceptions

Exceptions can be class or string objects. While most exceptions have traditionally been string objects, in Python 1.5 all standard exceptions have been converted to class objects, and users are encouraged to do the same. The source code for those exceptions is present in the standard library-module exceptions; this module never needs to be imported explicitly.

For backward compatibility, when Python is invoked with the -X option, most standard exceptions are strings.[6] This option can run code that breaks because of the different semantics of class-based exceptions. The -X option will become obsolete in future Python versions, so the recommended solution is to fix the code.

Two distinct string objects with the same value are considered different exceptions. This forces programmers to use exception names rather than their string value when specifying exception handlers. The string value of all built-in exceptions is their name, but this isn’t a requirement for user-defined exceptions or exceptions defined by library modules.

For class exceptions, in a try statement with an except clause that mentions a particular class, that clause also handles any exception classes derived from that class (but not exception classes from which it is derived). Two exception classes that aren’t related via subclassing are never equivalent, even if they have the same name.

The built-in exceptions in the following list can be generated by the interpreter or built-in functions. Except ...

Get Python Programming On Win32 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.