Skip to content

bpo-37826: Document exception chaining in Python tutorial for errors. #15243

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 14, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions Doc/tutorial/errors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,53 @@ re-raise the exception::
NameError: HiThere


.. _tut-exception-chaining:

Exception Chaining
==================

The :keyword:`raise` statement allows an optional :keyword:`from` which enables
chaining exceptions by setting the ``__cause__`` attribute of the raised
exception. For example::

raise RuntimeError from OSError

This can be useful when you are transforming exceptions. For example::

>>> def func():
... raise IOError
...
>>> try:
... func()
... except IOError as exc:
... raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in func
OSError
<BLANKLINE>
The above exception was the direct cause of the following exception:
<BLANKLINE>
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError

The expression following the :keyword:`from` must be either an exception or
``None``. Exception chaining happens automatically when an exception is raised
inside an exception handler or :keyword:`finally` section. Exception chaining
can be disabled by using ``from None`` idiom:

>>> try:
... open('database.sqlite')
... except IOError:
... raise RuntimeError from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError


.. _tut-userexceptions:

User-defined Exceptions
Expand Down