This section describes the exceptions that Python might raise during a program’s execution. Beginning with Python 1.5, all built-in exceptions are class objects (prior to 1.5 they were strings). Built-in exceptions are provided in the built-in scope namespace. Many built-in exceptions have associated state information that provides exception details.
The following exceptions are used only as superclasses for other exceptions.
BaseException
The root superclass for all built-in exceptions. It is
not meant to be directly inherited by user-defined classes; use
Exception
for this role
instead. If str()
is called
on an instance of this class, the representation of the
constructor argument(s) passed when creating the instance are
returned (or the empty string if there were no such arguments).
These instance constructor arguments are stored and made
available in the instance’s args
attribute as a tuple. Subclasses
inherit this protocol.
Exception
The root superclass for all built-in and
non-system-exiting exceptions. This is a direct subclass of
BaseException
.
User-defined exceptions should inherit (be derived) from this class. This derivation is required for user-defined exceptions in Python 3.0; Python 2.6 requires this of new-style classes, but also allows standalone exception classes.
try
statements that
catch this exception will catch all but system exit events,
because this class is superclass to all exceptions but SystemExit
, KeyboardInterrupt
, and GeneratorExit
(these three derive directly from BaseException
instead).
ArithmeticError
Arithmetic error exceptions category: the superclass of OverflowError
, ZeroDivisionError
, and FloatingPointError
, and a
subclass of Exception
.
LookupError
Sequence and mapping index errors: the superclass for
IndexError
and KeyError
, and a subclass of Exception
.
EnvironmentError
The category for exceptions that occur outside Python:
the superclass for IOError
and OSError
, and a subclass
of Exception
. The raised
instance includes informational attributes errno
and strerror
(and possible filename
for exceptions involving file
paths), which are also in args
.
The following classes are exceptions that are actually
raised. In addition, NameError
,
RuntimeError
, SyntaxError
, ValueError
, and Warning
are specific exceptions and
superclasses to other built-in exceptions.
AssertionError
AttributeError
EOFError
Raised when the immediate end-of-file is hit by input()
(or raw_input()
in Python 2). File read
methods return an empty object at end of file instead.
FloatingPointError
GeneratorExit
Raised when a generator’s close()
method is called. This
directly inherits from BaseException
instead of Exception
since it is not an
error.
IOError
Raised on I/O or file-related operation failures. Derived from
EnvironmentError
with state
information described above.
ImportError
Raised when an import
or from
fails to find a
module or attribute.
IndentationError
Raised when improper indentation is found in source code.
Derived from SyntaxError
.
IndexError
Raised on out-of-range sequence offsets (fetch or
assign). Slice indexes are silently adjusted to fall in the
allowed range; if an index is not an integer, TypeError
is raised.
KeyError
Raised on references to nonexistent mapping keys (fetch). Assignment to a nonexistent key creates that key.
KeyboardInterrupt
Raised on user entry of the interrupt key (normally
Ctrl-C or Delete). During execution, a check for interrupts is
made regularly. This exception inherits directly from BaseException
to
prevent it from being accidentally caught by code that catches
Exception
and thus prevents
interpreter exit.
MemoryError
Raised on recoverable memory exhaustion. This causes a stack-trace to be displayed if a runaway program was its cause.
NameError
Raised on failures to find a local or global unqualified name.
NotImplementedError
Raised on failures to define expected protocols. Abstract
class methods may raise this when they require a method to be
redefined. Derived from RuntimeError
. (This is not to be
confused with NotImplemented
,
a special built-in object returned by some operator-overloading
methods when operand types are not supported.)
OSError
Raised on os
module
errors (its os.error
exception). Derived from EnvironmentError
with state
information described
earlier.
OverflowError
Raised on excessively large arithmetic operations. This cannot occur for integers as they support arbitrary precision, and most floating-point operations are not checked either.
ReferenceError
Raised in conjunction with weak references. See the weakref
module.
RuntimeError
StopIteration
Raised on the end of values progression in iterator
objects. Raised by the next(X)
built-in and X.__next__()
methods (X.next()
in Python 2).
SyntaxError
Raised when parsers encounter a syntax error. This may
occur during import operations, calls to eval()
and exec()
, and when reading code in a
top-level script file or standard input. Instances of this class
have attributes filename
, lineno
, offset
, and text
for access to details; str()
of the exception instance
returns only the message.
SystemError
Raised on interpreter internal errors that are not serious enough to shut down (these should be reported).
SystemExit
Raised on a call to sys.exit(N)
. If not handled, the
Python interpreter exits, and no stack traceback is printed. If
the passed value is an integer, it specifies the system exit
status (passed on to C’s exit function); if it is None
, the exit status is zero; if it
has another type, the object’s value is printed and the exit
status is one. Derived directly from BaseException
to prevent it from
being accidentally caught by code that catches Exception
and thus prevents
interpreter exit.
sys.exit()
raises this
exception so that clean-up handlers (finally
clauses of try
statements) are executed, and so
that a debugger can execute a script without losing control. The
os._exit()
function exits
immediately when needed (e.g., in the child process after a call
to fork()
). Also see the
atexit
standard library
module for exit function specification.
TabError
Raised when an improper mixture of spaces and tabs is
found in source code. Derived from IndentationError
.
TypeError
Raised when an operation or function is applied to an object of inappropriate type.
UnboundLocalError
Raised on references to local names that have not yet
been assigned a value. Derived from NameError
.
UnicodeError
Raised on Unicode-related encoding or decoding errors; a
superclass category, and a subclass of ValueError
.
UnicodeEncodeError
UnicodeDecodeError
UnicodeTranslateError
Raised on Unicode-related processing errors; subclasses
of UnicodeError
.
ValueError
Raised when a built-in operation or function receives an
argument that has the correct type but an inappropriate value,
and the situation is not described by a more specific exception
like IndexError
.
WindowsError
ZeroDivisionError
Raised on division or modulus operations with 0 on the right.
The following exceptions are used as warning categories:
Warning
The superclass for all of the following warning
categories; it is a direct subclass of Exception
.
UserWarning
DeprecationWarning
PendingDeprecationWarning
Warnings about features that will be deprecated in the future.
SyntaxWarning
RuntimeWarning
FutureWarning
Warnings about constructs that will change semantically in the future.
ImportWarning
UnicodeWarning
BytesWarning
Warnings are issued when future language changes might break
existing code in a future Python release—and in other contexts.
Warnings may be configured to print messages, raise exceptions, or be
ignored. The warnings framework can be used to issue warnings by
calling the warnings.warn
function:
warnings.warn("feature obsolete", DeprecationWarning)
In addition, you can add filters to disable certain warnings.
You can apply a regular expression pattern to a message or module name
to suppress warnings with varying degrees of generality. For example,
you can suppress a warning about the use of the deprecated regex
module by calling:
import warnings warnings.filterwarnings(action = 'ignore', message='.*regex module*', category=DeprecationWarning, module = '__main__')
This adds a filter that affects only warnings of the class
DeprecationWarning
triggered in the
__main__
module, applies a regular
expression to match only the message that names the regex
module being deprecated, and causes
such warnings to be ignored. Warnings can also be printed only once,
printed every time the offending code is executed, or turned into
exceptions that will cause the program to stop (unless the exceptions
are caught). See the warnings
module documentation in version 2.1 and later for more information.
See also the -W
argument in the
section Command-Line Options.