Possible Duplicate:
Don't show Python raise-line in the exception stack
Built in exceptions like NameError
etc. give me a traceback to the point in my code where the exception occurred. I'm working on a utility module and it bugs me that if code using my module raises and exception the last thing in the traceback before the exception is my raise WhateverError
.
Is there any way to raise an exception in python and have the tracback stop one frame up ala the builtin exceptions (without writing c code)?
Let's consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement.
Only an exception handler (or a function that a handler calls, directly or indirectly) can use raise without any expressions.
Throwing exceptions manually There are two types of exceptions user defined and predefined each exception is represented by a class and which inherits the Throwable class. To throw an exception explicitly you need to instantiate the class of it and throw its object using the throw keyword.
except block is completed and the program will proceed. However, if an exception is raised in the try clause, Python will stop executing any more code in that clause, and pass the exception to the except clause to see if this particular error is handled there.
Pure Python doesn't provide a way to mutate existing traceback objects or create arbitrary traceback objects.
>>> exc_info[2].tb_next = None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: readonly attribute
>>> types.TracebackType()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create 'traceback' instances
Note that if it were possible to do this you wouldn't just affect the default formatting of tracebacks, you'd also interfere with people's ability to use pdb to post-mortem errors in your utility module.
If the traceback is being logged or otherwise formatted by your utility module then you can just not include the frames you consider uninteresting in the output. For instance, the standard library's unittest
module does this when reporting errors that occur while running tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With