Built-in Exceptions¶
In Python, all exceptions must be instances of a class that derives from
BaseException. 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 are not related via subclassing are never
equivalent, even if they have the same name.
The built-in exceptions listed in this chapter can be generated by the interpreter or built-in functions. Except where mentioned, they have an “associated value” indicating the detailed cause of the error. This may be a string or a tuple of several items of information (e.g., an error code and a string explaining the code). The associated value is usually passed as arguments to the exception class’s constructor.
User code can raise built-in exceptions. This can be used to test an exception handler or to report an error condition “just like” the situation in which the interpreter raises the same exception; but beware that there is nothing to prevent user code from raising an inappropriate error.
The built-in exception classes can be subclassed to define new exceptions;
programmers are encouraged to derive new exceptions from the Exception
class or one of its subclasses, and not from BaseException. More
information on defining exceptions is available in the Python Tutorial under
User-defined Exceptions.
Exception context¶
Three attributes on exception objects provide information about the context in which the exception was raised:
- BaseException.__context__¶
- BaseException.__cause__¶
- BaseException.__suppress_context__¶
When raising a new exception while another exception is already being handled, the new exception’s
__context__attribute is automatically set to the handled exception. An exception may be handled when anexceptorfinallyclause, or awithstatement, is used.This implicit exception context can be supplemented with an explicit cause by using
fromwithraise:raise new_exc from original_exc
The expression following
frommust be an exception orNone. It will be set as__cause__on the raised exception. Setting__cause__also implicitly sets the__suppress_context__attribute toTrue, so that usingraise new_exc from Noneeffectively replaces the old exception with the new one for display purposes (e.g. convertingKeyErrortoAttributeError), while leaving the old exception available in__context__for introspection when debugging.The default traceback display code shows these chained exceptions in addition to the traceback for the exception itself. An explicitly chained exception in
__cause__is always shown when present. An implicitly chained exception in__context__is shown only if__cause__isNoneand__suppress_context__is false.In either case, the exception itself is always shown after any chained exceptions so that the final line of the traceback always shows the last exception that was raised.
Inheriting from built-in exceptions¶
User code can create subclasses that inherit from an exception type.
It’s recommended to only subclass one exception type at a time to avoid
any possible conflicts between how the bases handle the args
attribute, as well as due to possible memory layout incompatibilities.
CPython implementation detail: Most built-in exceptions are implemented in C for efficiency, see: Objects/exceptions.c. Some have custom memory layouts which makes it impossible to create a subclass that inherits from multiple exception types. The memory layout of a type is an implementation detail and might change between Python versions, leading to new conflicts in the future. Therefore, it’s recommended to avoid subclassing multiple exception types altogether.
Base classes¶
The following exceptions are used mostly as base classes for other exceptions.
- exception BaseException¶
The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use
Exception). Ifstr()is called on an instance of this class, the representation of the argument(s) to the instance are returned, or the empty string when there were no arguments.- args¶
The tuple of arguments given to the exception constructor. Some built-in exceptions (like
OSError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message.
- with_traceback(tb)¶
This method sets tb as the new traceback for the exception and returns the exception object. It was more commonly used before the exception chaining features of PEP 3134 became available. The following example shows how we can convert an instance of
SomeExceptioninto an instance ofOtherExceptionwhile preserving the traceback. Once raised, the current frame is pushed onto the traceback of theOtherException, as would have happened to the traceback of the originalSomeExceptionhad we allowed it to propagate to the caller.try: ... except SomeException: tb = sys.exception().__traceback__ raise OtherException(...).with_traceback(tb)
- __traceback__¶
A writable field that holds the traceback object associated with this exception. See also: The raise statement.
- add_note(note)¶
Add the string
noteto the exception’s notes which appear in the standard traceback after the exception string. ATypeErroris raised ifnoteis not a string.Added in version 3.11.
- __notes__¶
A list of the notes of this exception, which were added with
add_note(). This attribute is created whenadd_note()is called.Added in version 3.11.
- exception Exception¶
All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.
- exception ArithmeticError¶
The base class for those built-in exceptions that are raised for various arithmetic errors:
OverflowError,ZeroDivisionError,FloatingPointError.
- exception LookupError¶
The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid:
IndexError,KeyError. This can be raised directly bycodecs.lookup().
Concrete exceptions¶
The following exceptions are the exceptions that are usually raised.
- exception AttributeError¶
Raised when an attribute reference (see Attribute references) or assignment fails. (When an object does not support attribute references or attribute assignments at all,
TypeErroris raised.)The optional name and obj keyword-only arguments set the corresponding attributes:
- name¶
The name of the attribute that was attempted to be accessed.
- obj¶
The object that was accessed for the named attribute.
- exception EOFError¶
Raised when the
input()function hits an end-of-file condition (EOF) without reading any data. (Note: theio.TextIOBase.read()andio.IOBase.readline()methods return an empty string when they hit EOF.)
- exception FloatingPointError¶
Not currently used.
- exception GeneratorExit¶
Raised when a generator or coroutine is closed; see
generator.close()andcoroutine.close(). It directly inherits fromBaseExceptioninstead ofExceptionsince it is technically not an error.
- exception ImportError¶
Raised when the
importstatement has troubles trying to load a module. Also raised when the “from list” infrom ... importhas a name that cannot be found.The optional name and path keyword-only arguments set the corresponding attributes:
- name¶
The name of the module that was attempted to be imported.
- path¶
The path to any file which triggered the exception.
- exception ModuleNotFoundError¶
A subclass of
ImportErrorwhich is raised byimportwhen a module could not be located. It is also raised whenNoneis found insys.modules.Added in version 3.6.
- exception IndexError¶
Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the allowed range; if an index is not an integer,
TypeErroris raised.)
- exception KeyError¶
Raised when a mapping (dictionary) key is not found in the set of existing keys.
- exception KeyboardInterrupt¶
Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. The exception inherits from
BaseExceptionso as to not be accidentally caught by code that catchesExceptionand thus prevent the interpreter from exiting.Note
Catching a
KeyboardInterruptrequires special consideration. Because it can be raised at unpredictable points, it may, in some circumstances, leave the running program in an inconsistent state. It is generally best to allowKeyboardInterruptto end the program as quickly as possible or avoid raising it entirely. (See Note on Signal Handlers and Exceptions.)
- exception MemoryError¶
Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). The associated value is a string indicating what kind of (internal) operation ran out of memory. Note that because of the underlying memory management architecture (C’s
malloc()function), the interpreter may not always be able to completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a run-away program was the cause.
- exception NameError¶
Raised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found.
The optional name keyword-only argument sets the attribute:
- name¶
The name of the variable that was attempted to be accessed.
Changed in version 3.10: Added the
nameattribute.
- exception NotImplementedError¶
This exception is derived from
RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added.Note
It should not be used to indicate that an operator or method is not meant to be supported at all – in that case either leave the operator / method undefined or, if a subclass, set it to