[Python-Dev] with_traceback

James Y Knight foom at fuhm.net
Thu Mar 1 05:15:24 CET 2007

On Feb 28, 2007, at 9:10 PM, Guido van Rossum wrote:
> I am beginning to think that there are serious problems with attaching
> the traceback to the exception; I really don't like the answer that
> pre-creating an exception is unpythonic in Py3k.

I'll say up front that I haven't been paying as much attention to the  
topic of exception behavior as perhaps I should before attempting to  
contribute to a thread about it...but...

It seems to me that a stack trace should always be attached to an  
exception object at creation time of the exception, and never at any  
other time. Then, if someone pre-creates an exception object, they  
get consistent and easily explainable behavior (the traceback to the  
creation point). The traceback won't necessarily be *useful*, but  
presumably someone pre-creating an exception object did so to save  
run-time, and creating the traceback is generally very expensive, so  
doing that only once, too, seems like a win to me.

FWIW, that's basically how exceptions work in Java.
 From http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Throwable.html:
> Instances of two subclasses, Error and Exception, are  
> conventionally used to indicate that exceptional situations have  
> occurred. Typically, these instances are freshly created in the  
> context of the exceptional situation so as to include relevant  
> information (such as stack trace data).

> A throwable contains a snapshot of the execution stack of its  
> thread at the time it was created. It can also contain a message  
> string that gives more information about the error. Finally, it can  
> contain a cause: another throwable that caused this throwable to  
> get thrown. The cause facility is new in release 1.4. It is also  
> known as the chained exception facility, as the cause can, itself,  
> have a cause, and so on, leading to a "chain" of exceptions, each  
> caused by another.

There's probably a million reasons why this doesn't work for python,  
but they don't immediately jump out at me. :)

Migration from 2.X to 3.X would consist of recommending not to create  
an exception outside of a raise line, unless you're okay with the  
traceback location changing from the raise point to the creation point.


More information about the Python-Dev mailing list