12

I'm trying to catch an exception and raise a more specific error at a point in my code:

try:
  something_crazy()
except SomeReallyVagueError:
  raise ABetterError('message')

This works in Python 2, but in Python 3, it shows both exceptions:

Traceback(most recent call last):
...
SomeReallyVagueError: ...
...

During handling of the above exception, another exception occurred:

Traceback(most recent call last):
...
ABetterError: message
...

Is there some way to get around this, so that SomeReallyVagueError's traceback isn't shown?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
kirbyfan64sos
  • 10,377
  • 6
  • 54
  • 75

1 Answers1

17

In Python versions 3.3 and greater, you can use the raise <exception> from None syntax to suppress the traceback of the first exception:

>>> try:
...     1/0
... except ZeroDivisionError:
...     raise ValueError
...
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>
ValueError
>>>
>>>
>>> try:
...     1/0
... except ZeroDivisionError:
...     raise ValueError from None
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError
>>>