Skip to content

Instantly share code, notes, and snippets.

@ulope
Last active April 13, 2021 14:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ulope/1d752ad755f123f07c4ee67ba016092c to your computer and use it in GitHub Desktop.
Save ulope/1d752ad755f123f07c4ee67ba016092c to your computer and use it in GitHub Desktop.
Python exception chaining
def implicit_chaining():
"""
This is the Python 2 style. Just raising another exception from within an except block.
In Python 3 this causes the exceptions to be chained with the message:
During handling of the above exception, another exception occurred:
Which is usually not correct when just re-raising with a more appropriate type.
"""
try:
1/0
except Exception:
raise RuntimeError('Something')
implicit_chaining()
Traceback (most recent call last):
File "implicit_chaining.py", line 11, in implicit_chaining
1/0
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "implicit_chaining.py", line 15, in <module>
implicit_chaining()
File "implicit_chaining.py", line 13, in implicit_chaining
raise RuntimeError('Something')
RuntimeError: Something
def explicit_chaining():
"""
This is the syntax to show that an exception has been caused by a previous one
but it's not unexpected like in the previous example.
The message used to chain the exception tracebacks in this case will be:
The above exception was the direct cause of the following exception:
This is useful when the original exception may contain information that can be helpful
in debugging the issue etc.
"""
try:
1/0
except Exception as ex:
raise RuntimeError('Something') from ex
explicit_chaining()
Traceback (most recent call last):
File "explicit_chaining.py", line 10, in explicit_chaining
1/0
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "explicit_chaining.py", line 14, in <module>
explicit_chaining()
File "explicit_chaining.py", line 12, in explicit_chaining
raise RuntimeError('Something') from ex
RuntimeError: Something
def suppress_chaining():
"""
This will suppress any exceptions further down in the call stack and is
usually the preferred way in order to keep tracebacks short, unless
the 'parent' exceptions are useful to debugging as described above.
"""
try:
1/0
except Exception:
raise RuntimeError('Something') from None
suppress_chaining()
Traceback (most recent call last):
File "suppress_chaining.py", line 13, in <module>
suppress_chaining()
File "suppress_chaining.py", line 11, in suppress_chaining
raise RuntimeError('Something') from None
RuntimeError: Something
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment