mirror of
https://github.com/python/cpython.git
synced 2025-10-08 16:11:51 +00:00
[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 395b66a0ae
)
Co-authored-by: Shahriar Heidrich <smheidrich@weltenfunktion.de>
This commit is contained in:
parent
2af22d2205
commit
82f663b7f0
1 changed files with 23 additions and 5 deletions
|
@ -284,8 +284,27 @@ re-raise the exception::
|
||||||
Exception Chaining
|
Exception Chaining
|
||||||
==================
|
==================
|
||||||
|
|
||||||
The :keyword:`raise` statement allows an optional :keyword:`from<raise>` which enables
|
If an unhandled exception occurs inside an :keyword:`except` section, it will
|
||||||
chaining exceptions. For example::
|
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.
|
# exc must be exception instance or None.
|
||||||
raise RuntimeError from exc
|
raise RuntimeError from exc
|
||||||
|
@ -311,9 +330,8 @@ This can be useful when you are transforming exceptions. For example::
|
||||||
File "<stdin>", line 4, in <module>
|
File "<stdin>", line 4, in <module>
|
||||||
RuntimeError: Failed to open database
|
RuntimeError: Failed to open database
|
||||||
|
|
||||||
Exception chaining happens automatically when an exception is raised inside an
|
It also allows disabling automatic exception chaining using the ``from None``
|
||||||
:keyword:`except` or :keyword:`finally` section. This can be
|
idiom::
|
||||||
disabled by using ``from None`` idiom:
|
|
||||||
|
|
||||||
>>> try:
|
>>> try:
|
||||||
... open('database.sqlite')
|
... open('database.sqlite')
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue