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 when