2

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..

3
  • It sounds like you want to change the representation of the exception and not the exception itself. Commented May 28, 2018 at 12:29
  • 1
    The most pythonic thing to do here is to leave the original exception and traceback alone. As far as I'm concerned I just positively HATE it when someone think he's smart enough to know which parts of the original exception / original traceback are going to be useful to ME. It just happens that I have this exact issue right now with some inept exception handler in reportlab that prevents me from getting needed infos to fix a critical bug on our product, and I'll have to actually fork the whole project and deploy this fork on production just to get the original exception and full traceback. Commented May 28, 2018 at 12:32
  • 1
    I don't want to change exception representation in general but in a few cases where it's very clear that just the local context is needed to find the problem (e.g. a get(<name>) function with a deeply nested lookup resulting in a very obvious KeyError. In pytest scenarios with thousands of tests you sometimes have hundreds of megabytes of useless stack trace with 99% repeated information which make it very hard to find the actual problem. Commented May 28, 2018 at 12:44

1 Answer 1

5

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.