Skip to content
Browse files

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

  • Loading branch information...
maxking authored and miss-islington committed Aug 14, 2019
1 parent 71662dc commit dcfe111eb5602333135b8776996332a8dcf59392
Showing with 47 additions and 0 deletions.
  1. +47 −0 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
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>

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>

.. _tut-userexceptions:

User-defined Exceptions

0 comments on commit dcfe111

Please sign in to comment.
You can’t perform that action at this time.