1

I have a script in Python 3, which re-raises an exception using the 'from' keyword (as demonstrated in the answer to this Stackoverflow question: Re-raise exception with a different type and message, preserving existing information )

I have to go back now and make the script compatible with Python 2.7. The 'from' keyword can not be used this way in Python 2.7. I found that in Python 2, the way to re-raise an exception is as follows:

try:
    foo()
except ZeroDivisionError as e:
    import sys
    raise MyCustomException, MyCustomException(e), sys.exc_info()[2]

However, while this syntax works in Python 2.7, it does not work for Python 3.

Is there an accepted way to re-raise exceptions in Python which work for both Python 2.7 and Python 3?

ffConundrums
  • 765
  • 9
  • 24

1 Answers1

3
# Python 3 only
try:
    frobnicate()
except KeyError as exc:
    raise ValueError("Bad grape") from exc

# Python 2 and 3:
from future.utils import raise_from

try:
    frobnicate()
except KeyError as exc:
    raise_from(ValueError("Bad grape"), exc)
GP89
  • 6,600
  • 4
  • 36
  • 64