Tuesday, December 6, 2016

Did you know about `raise .. from ...` in Python 3?


Python 3.5.2 (default, Oct 11 2016, 04:59:56)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin

>>> try:
...     1/0
... except Exception as exc:
...     raise RuntimeError('Something bad happened')
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened
>>> try:
...     1/0
... except Exception as exc:
...     raise RuntimeError('Something bad happened') from exc
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened
>>> try:
...     1/0
... except Exception as exc:
...     raise RuntimeError('Something bad happened') from None
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened
>>>

Related info:

No comments:

Post a Comment