XD blog

blog page

exception, python, stack


2013-12-06 Extend the exception stack in Python

Most of the time, message given by exception are not enough precise to quickly understand the error. To add more information, I used to catch it and throw a new one:

try :
    # something
except Exception as e :
    message = "my message with more information \n" + str(e)
    raise Exception(message) 

However, it is possible to do this:

try :
    # something
except Exception as e :
    message = "my message with more information"
    raise Exception(message) from e

It does not break the exception stack as before. The new exception is just added to it.

In the following example, I added a message which shows the content of variable x and y.

x,y = 5,3
try :
    z = 1 / (y**2 -2*y + 1 - (y-1)**2)
except Exception as e :
    message = "computation error with number x={0}, y={1}".format(x,y)
    raise Exception(message) from e

The exception stack is:

Traceback (most recent call last):
  File "y.py", line 3, in <module>
    z = 1 / (y**2 -2*y + 1 - (y-1)**2)
ZeroDivisionError: division by zero

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

Traceback (most recent call last):
  File "y.py", line 6, in <module>
    raise Exception(message) from e
Exception: computation error with number x=5, y=3

<-- -->

Xavier Dupré