1

I have a Python code where I want to catch all possible exceptions and rise my own custom exception, but conserving as much information as possible.

In Python 3, there is a construct raise from that does more or less what I want

def function():
    return 1 / 0

class MyException(Exception):
    pass

try:
    function()
except Exception as err:
    raise MyException(err) from err

Output is

Traceback (most recent call last):
  File "capture.py", line 9, in <module>
   function()
  File "capture.py", line 3, in function
    return 1 / 0
ZeroDivisionError: division by zero

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

Traceback (most recent call last):
  File "capture.py", line 11, in <module>
    raise MyException(err) from err
__main__.MyException: division by zero

Is there a way to obtain similar result in Python 2?

So, for future reference, the answer is yes. Given the answer in the linked question, what I want can be achieved with the following code

import sys

def function():
    return 1 / 0

class MyException(Exception):
    pass

try:
    function()
except Exception as err:
    raise MyException, err, sys.exc_info()[2]
Sergio
  • 677
  • 1
  • 10
  • 20

0 Answers0