Python Language Exceptions are Objects too


Example

Exceptions are just regular Python objects that inherit from the built-in BaseException. A Python script can use the raise statement to interrupt execution, causing Python to print a stack trace of the call stack at that point and a representation of the exception instance. For example:

>>> def failing_function():
...     raise ValueError('Example error!')
>>> failing_function()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in failing_function
ValueError: Example error!

which says that a ValueError with the message 'Example error!' was raised by our failing_function(), which was executed in the interpreter.

Calling code can choose to handle any and all types of exception that a call can raise:

>>> try:
...     failing_function()
... except ValueError:
...     print('Handled the error')
Handled the error

You can get hold of the exception objects by assigning them in the except... part of the exception handling code:

>>> try:
...     failing_function()
... except ValueError as e:
...     print('Caught exception', repr(e))
Caught exception ValueError('Example error!',)

A complete list of built-in Python exceptions along with their descriptions can be found in the Python Documentation: https://docs.python.org/3.5/library/exceptions.html. And here is the full list arranged hierarchically: Exception Hierarchy.