Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Passing In Python

I have a bit of code that does some functional exception handling and everything works well, exceptions are raised when I want them to be, but when I'm debugging, the line-traces don't always do quite what I want them to.

Example A:

>>> 3/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

Example B:

>>> try: 3/0
... except Exception as e: raise e
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

In both of these examples, the exception really occurs in line 1, where we attempt to do 3/0, but in the latter example, we are told it has occurred on line 2, where it is raised.

Is there a way in Python to raise an exception, as if it were another exception, something that would produce the following output:

>>> try: 3/0
... except Exception as e: metaraise(e)
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
like image 309
Kevin Dolan Avatar asked Jan 19 '11 00:01

Kevin Dolan


1 Answers

When you re-raise an exception that you caught, such as

except Exception as e: raise e

it resets the stack trace. It's just like re-raising a new exception. What you want is this:

except Exception as e: raise
like image 157
Falmarri Avatar answered Oct 05 '22 17:10

Falmarri