Skip to content

gh-97654: Add auto exception chaining example to tutorial #97703

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 1 commit into from
Oct 5, 2022
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
28 changes: 23 additions & 5 deletions Doc/tutorial/errors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -284,8 +284,27 @@ re-raise the exception::
Exception Chaining
==================

The :keyword:`raise` statement allows an optional :keyword:`from<raise>` which enables
chaining exceptions. For example::
If an unhandled exception occurs inside an :keyword:`except` section, it will
have the exception being handled attached to it and included in the error
message::

>>> try:
... open("database.sqlite")
... except OSError:
... raise RuntimeError("unable to handle error")
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'database.sqlite'
<BLANKLINE>
During handling of the above exception, another exception occurred:
<BLANKLINE>
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: unable to handle error

To indicate that an exception is a direct consequence of another, the
:keyword:`raise` statement allows an optional :keyword:`from<raise>` clause::

# exc must be exception instance or None.
raise RuntimeError from exc
Expand All @@ -311,9 +330,8 @@ This can be useful when you are transforming exceptions. For example::
File "<stdin>", line 4, in <module>
RuntimeError: Failed to open database

Exception chaining happens automatically when an exception is raised inside an
:keyword:`except` or :keyword:`finally` section. This can be
disabled by using ``from None`` idiom:
It also allows disabling automatic exception chaining using the ``from None``
idiom::

>>> try:
... open('database.sqlite')
Expand Down