Built-in Exceptions
Docs: https://docs.python.org/3.10/library/exceptions.html#built-in-exceptions
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
When raising (or re-raising) an exception in an except or finally clause __context__
is automatically set to the last exception caught; if the new exception is not handled the traceback that is
eventually displayed will include the originating exception(s) and the final exception.
When raising a new exception (rather than using a bare raise
to re-raise the exception currently being handled), the
implicit exception context can be supplemented with an explicit cause by using from with raise.
def outer():
try:
inner()
except Exception as err:
err_name = f'{err.__class__.__module__}.{err.__class__.__name__}'
print(f'Catched in outer: {err_name}; {str(err)}')
raise ValueError from err
finally:
print('outer finally')
def inner():
try:
1 / 0
except ZeroDivisionError as err:
err_name = f'{err.__class__.__module__}.{err.__class__.__name__}'
print(f'Catched in inner: {err_name}; {str(err)}')
raise err
finally:
print('inner finally')
def main():
outer()
if __name__ == '__main__':
main()
Traceback (most recent call last):
File "exceptions.py", line 3, in outer
inner()
File "exceptions.py", line 16, in inner
raise err
File "exceptions.py", line 13, in inner
1 / 0
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "exceptions.py", line 24, in <module>
main()
File "exceptions.py", line 21, in main
outer()
File "exceptions.py", line 6, in outer
raise ValueError from err
ValueError
Catched in inner: builtins.ZeroDivisionError; division by zero
inner finally
Catched in outer: builtins.ZeroDivisionError; division by zero
outer finally
Note
Passing arguments of the wrong type (e.g. passing a list
when an int
is expected) should result in a
TypeError
, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result
in a ValueError
.
Exception hierarchy
The class hierarchy for built-in exceptions is:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- EncodingWarning
+-- ResourceWarning