Skip to content

Commit 9f1c9b1

Browse files
[3.10] gh-97654: Add auto exception chaining example to tutorial (GH-97703) (#97884)
Add auto exception chaining example to tutorial (cherry picked from commit 395b66a) Co-authored-by: Shahriar Heidrich <[email protected]>
1 parent 3b0f2a7 commit 9f1c9b1

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

Doc/tutorial/errors.rst

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -275,8 +275,27 @@ re-raise the exception::
275275
Exception Chaining
276276
==================
277277

278-
The :keyword:`raise` statement allows an optional :keyword:`from<raise>` which enables
279-
chaining exceptions. For example::
278+
If an unhandled exception occurs inside an :keyword:`except` section, it will
279+
have the exception being handled attached to it and included in the error
280+
message::
281+
282+
>>> try:
283+
... open("database.sqlite")
284+
... except OSError:
285+
... raise RuntimeError("unable to handle error")
286+
...
287+
Traceback (most recent call last):
288+
File "<stdin>", line 2, in <module>
289+
FileNotFoundError: [Errno 2] No such file or directory: 'database.sqlite'
290+
<BLANKLINE>
291+
During handling of the above exception, another exception occurred:
292+
<BLANKLINE>
293+
Traceback (most recent call last):
294+
File "<stdin>", line 4, in <module>
295+
RuntimeError: unable to handle error
296+
297+
To indicate that an exception is a direct consequence of another, the
298+
:keyword:`raise` statement allows an optional :keyword:`from<raise>` clause::
280299

281300
# exc must be exception instance or None.
282301
raise RuntimeError from exc
@@ -302,9 +321,8 @@ This can be useful when you are transforming exceptions. For example::
302321
File "<stdin>", line 4, in <module>
303322
RuntimeError: Failed to open database
304323

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

309327
>>> try:
310328
... open('database.sqlite')

0 commit comments

Comments
 (0)