Python Raise Error With Traceback
Contents |
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company Business Learn python 2 exception chaining more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags python raise arguments Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just like you, python exception traceback helping each other. Join them; it only takes a minute: Sign up “Inner exception” (with traceback) in Python? up vote 86 down vote favorite 31 My background is in C# and I've just recently started programming in python exception object Python. When an exception is thrown I typically want to wrap it in another exception that adds more information, while still showing the full stack trace. It's quite easy in C#, but how do I do it in Python? Eg. in C# I would do something like this: try { ProcessFile(filePath); } catch (Exception ex) { throw new ApplicationException("Failed to process file " + filePath, ex); } In Python I can do something similar: try: ProcessFile(filePath)
Python Reraise Exception
except Exception as e: raise Exception('Failed to process file ' + filePath, e) ...but this loses the traceback of the inner exception! Edit: I'd like to see both exception messages and both stack traces and correlate the two. That is, I want to see in the output that exception X occurred here and then exception Y there - same as I would in C#. Is this possible in Python 2.6? Looks like the best I can do so far (based on Glenn Maynard's answer) is: try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file' + filePath, e), None, sys.exc_info()[2] This includes both the messages and both the tracebacks, but it doesn't show which exception occurred where in the traceback. python exception error-handling share|improve this question edited Aug 31 '09 at 0:16 asked Aug 29 '09 at 6:35 EMP 23.5k33129192 add a comment| 8 Answers 8 active oldest votes up vote 97 down vote accepted It's simple; pass the traceback as the third argument to raise. import sys class MyException(Exception): pass try: raise TypeError("test") except TypeError, e: raise MyException(), None, sys.exc_info()[2] Always do this when catching one exception and re-raising another. share|improve this answer edited Aug 29 '09 at 10:05 answered Aug 29 '09 at 9:41 Glenn Maynard 33.5k368108 1 Thanks. That preserves the traceback, but it loses the error message of the origin
you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax errors and exceptions. 8.1. Syntax Errors¶ Syntax errors, also
Python Re Raise Exception With Message
known as parsing errors, are perhaps the most common kind of complaint you print exception python get while you are still learning Python: >>> while True print 'Hello world' File "
home cookingPicturesA Walk on the Pequest FillAutumn in the GapBroken Pipe(dreams)Calno to Wallpack CenterChesapeake Cruise June 2008FJ CruisingIron Road to ChesterMillbrook Village and Mountain RoadOBX AdventureOld Dingmans and Sand Pond RoadsThe Depue and Kinney FarmsThe http://www.markbetz.net/2014/04/30/re-raising-exceptions-in-python/ Lehigh and Hudson RRThe Orchard Trail and Ridge RoadThe Paulins Kill ViaductThe http://nedbatchelder.com/blog/200711/rethrowing_exceptions_in_python.html Vancampen Burial Ground April 30, 2014November 14, 2014 Re-raising exceptions in Python I often run into situations where an error occurs, an exception is caught, and some action is taken before the exception is re-raised so that higher levels of the program can deal with it. Exactly how the python raise exception is re-raised can have a big impact on how much information is available to someone trying to debug a problem. I got this wrong as a newbie, and I've seen even experienced python programmers get tripped up by these subtleties so I thought I would try to post a clear example. Consider the following program: def bar(): raise Exception("Oops!") def python raise error foo(): bar() def dinkum(): foo() def fair(): try: dinkum() except Exception as e: print "Something failed!" raise e fair() As you can see I've created a few methods in order to have a stack trace to look at, and raised an exception in the last one to be called, foo(). That exception is caught in fair() and some information is printed before the exception is re-raised by the statement "raise e." This syntax looks pretty reasonable, so let's run it and see what happens: mark@viking:~/workspace$ python raise_test1.py Something failed! Traceback (most recent call last): File "raise_test.py", line 21, in fair() File "raise_test.py", line 19, in fair raise e Exception: Oops! Hmm. Looks like we're missing some useful information. The exception was raised on line 6 but the stack trace begins on line 19. Lets change the program slightly and run it again: def bar(): raise Exception("Oops!") # ... snip for brevity ... def fair(): try: dinkum() except Exception as e: print "Something failed!" raise fair() The only change here is that now we're simply using "raise" rather than re-raising the exception by
to be able to manipulate exceptions in ways other than simply throwing and catching them. One of these is to re-throw exceptions.The simplest way to do this is if you need to perform a little work after the catch, but then immediately re-throw. This can be done with a simple raise statement:try:
do_something_dangerous()
except:
do_something_to_apologize()
raise
Here the raise statement means, "throw the exception last caught". This is a simple case, and I probably didn't need to remind you of it. But a more sophisticated technique is to catch an exception in one place, and raise it again in another.For example, you may have a worker thread pre-fetching data from slow storage, and then on the main thread, the consumer of the data either gets the data or sees the exception that prevented him from getting the data. Here's the simple implementation: 1 class DelayedResult:
2 def __init__(self):
3 self.e = None
4 self.result = None
5