Skip to content

Commit 82f663b

Browse files
miss-islingtonsmheidrich
authored andcommitted
[3.11] gh-97654: Add auto exception chaining example to tutorial (GH-97703) (#97885)
gh-97654: Add auto exception chaining example to tutorial (GH-97703) Add auto exception chaining example to tutorial (cherry picked from commit 395b66a) Co-authored-by: Shahriar Heidrich <[email protected]>
1 parent 2af22d2 commit 82f663b

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

Doc/tutorial/errors.rst

+23-5
Original file line numberDiff line numberDiff line change
@@ -284,8 +284,27 @@ re-raise the exception::
284284
Exception Chaining
285285
==================
286286

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

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

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

318336
>>> try:
319337
... open('database.sqlite')

0 commit comments

Comments
 (0)