[Python-checkins] bpo-37826: Document exception chaining in Python tutorial for errors. (GH-15243)

Miss Islington (bot) webhook-mailer at python.org
Wed Aug 14 17:11:37 EDT 2019


https://github.com/python/cpython/commit/dcfe111eb5602333135b8776996332a8dcf59392
commit: dcfe111eb5602333135b8776996332a8dcf59392
branch: master
author: Abhilash Raj <maxking at users.noreply.github.com>
committer: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
date: 2019-08-14T14:11:32-07:00
summary:

bpo-37826: Document exception chaining in Python tutorial for errors. (GH-15243)



https://bugs.python.org/issue37826

files:
M Doc/tutorial/errors.rst

diff --git a/Doc/tutorial/errors.rst b/Doc/tutorial/errors.rst
index 4e287bbd8d29..e9a63e425279 100644
--- a/Doc/tutorial/errors.rst
+++ b/Doc/tutorial/errors.rst
@@ -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



More information about the Python-checkins mailing list