2.2. Exception Chain

2.2.1. Recap

  • except ... as ... - captures the exception object

>>> def run():
...     raise RuntimeError('Some message')
>>>
>>> try:
...     run()
... except RuntimeError as err:
...     print(f'Error: {err}')
...
Error: Some message

2.2.2. Reraise

  • You can reraise the exception using raise without arguments

>>> def run():
...     raise RuntimeError('Some message')
>>>
>>> try:
...     run()
... except RuntimeError as err:
...     # do something
...     raise
...
Traceback (most recent call last):
RuntimeError: Some message

2.2.3. Rethrow

  • You can rethrow the exception using raise with a new exception

>>> def run():
...     raise RuntimeError('Some message')
>>>
>>> try:
...     run()
... except RuntimeError as err:
...     # do something
...     raise PermissionError(f'Error: {err}')
...
Traceback (most recent call last):
RuntimeError: Some message

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
PermissionError: Error: Some message

2.2.4. Chaining

>>> def run():
...     raise RuntimeError('Some message')
>>>
>>>
>>> try:
...     run()
... except RuntimeError as err:
...     # do something
...     raise PermissionError('Error: Some message') from err
...
Traceback (most recent call last):
RuntimeError: Some message

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
PermissionError: Error: Some message

2.2.5. Silencing

>>> def run():
...     raise RuntimeError('Some message')
>>>
>>>
>>> try:
...     run()
... except RuntimeError as err:
...     # do something
...     raise PermissionError('Error: Some message') from None
...
Traceback (most recent call last):
PermissionError: Error: Some message

2.2.6. Further Reading

2.2.7. Assignments