1

Is there a way to provide information about the cause of an inner exception when passing it up the chain (like it's possible in java with the cause property of Exception class).

Please consider the following "python pseudo code" (without 100 % correct and invented function and class names)

try:
  clientlib.receive_data_chunk()
except ClientException as clientException:
  raise RuntimeError("reading from client failed" 
      + " (see nested exceptions for details)", cause=clientException)

and in clientlib.py

def receive_data_chunk():
  try:
    chunk = socket.read(20)
    return chunk
  except IOException as iOException:
    raise ClientException("couldn't read from client", cause = iOException)

If not within native python what would be best practice to achieve what I want to do?

Please note that I want to preserve both stacktraces of the inner and the outer exception, i.e. the following solution is not satisfying:

import sys

def function():
    try:
        raise ValueError("inner cause")
    except Exception:
        _, ex, traceback = sys.exc_info()
        message = "outer explanation (see nested exception for details)"
        raise RuntimeError, message, traceback

if __name__ == "__main__":
    function()

produces only the following output:

Traceback (most recent call last):
  File "a.py", line 13, in <module>
    function()
  File "a.py", line 6, in function
    raise ValueError("inner cause")
RuntimeError: outer explanation (see nested exception for details)

I cannot see where the RuntimeError occured, so in my understanding the outer stacktrace is lost.

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
  • See this (http://stackoverflow.com/questions/1350671/inner-exception-with-traceback-in-python) question which asks and answers what you want to know (just with different terms.) – wheaties Apr 18 '14 at 16:05
  • I agree. I guess it makes sense to edit the title of the referenced question in order to include the term `cause` to improve search because it is quiet widely used in java related issues. – Kalle Richter Apr 18 '14 at 16:18

1 Answers1

5

In Python 3, you can use the from keyword to specify an inner exception:

raise ClientException(...) from ioException

You get a traceback that looks like this:

Traceback (most recent call last):
  ...
IOException: timeout

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

Traceback (most recent call last):
  ...
ClientException: couldn't read from client
nneonneo
  • 171,345
  • 36
  • 312
  • 383