Search code examples
pythonexceptiontracebackbacktrace

How to re-raise the same exception without the traceback?


In an except block I want to raise the same exception but without the stack trace and without the information that this exception has been raised as direct cause of another exception. (and without modifying sys.tracebacklimit globally)

Additionally I have a very clumsy exception class which parses and modifies the message text so I can't just reproduce it.

My current approach is

try:
    deeply_nested_function_that_raises_exception()
except ClumsyExceptionBaseClass as exc:
    cls, code, msg = exc.__class__, exc.code, exc.msg
raise cls("Error: %d %s" % (code, msg))

What I'm doing here is de-composing the exception information, re-assemble a new exception with a message which will be parsed and split into error code and message in the constructor and raise it from outside the except block in order to forget all trace information.

Is there a more pythonic way to do this? All I want is get rid of the noisy (and useless in my case) trace back while keeping the information contained in the exception object..


Solution

  • In Python 3, you can use with_traceback to remove the traceback entries accumulated so far:

    try: ...
    except Exception as e:
      raise e.with_traceback(None)
    

    In Python 2, it’s just

    try: ...
    except Exception as e:
      raise e   # not just "raise"
    

    It will of course still show the trace to this line, since that’s added as the exception propagates (again).