PEP 344 – Exception Chaining and Embedded Tracebacks | peps.python.org
PEP 344 – Exception Chaining and Embedded Tracebacks PEP 344 – Exception Chaining and Embedded Tracebacks Author : Ka-Ping Yee Status : Superseded Type : Standards Track Created : 12-May-2005 Python-Version : 2.5 Post-History : Table of Contents Numbering Note Abstract Motivation History Rationale Implicit Exception Chaining Explicit Exception Chaining Traceback Attribute Enhanced Reporting C API Compatibility Open Issue: Extra Information Open Issue: Suppressing Context Open Issue: Limiting Exception Types Open Issue: yield Open Issue: Garbage Collection Possible Future Compatible Changes Possible Future Incompatible Changes Acknowledgements References Copyright Numbering Note This PEP has been renumbered to PEP 3134 .
The text below is the last version submitted under the old number. Abstract This PEP proposes three standard attributes on exception instances: the __context__ attribute for implicitly chained exceptions, the __cause__ attribute for explicitly chained exceptions, and the __traceback__ attribute for the traceback. A new raise ... from statement sets the __cause__ attribute. Motivation During the handling of one exception (exception A), it is possible that another exception (exception B) may occur.
In today’s Python (version 2.4), if this happens, exception B is propagated outward and exception A is lost. In order to debug the problem, it is useful to know about both exceptions. The __context__ attribute retains this information automatically. Sometimes it can be useful for an exception handler to intentionally re-raise an exception, either to provide extra information or to translate an exception to another type.
The __cause__ attribute provides an explicit way to record the direct cause of an exception. In today’s Python implementation, exceptions are composed of three parts: the type, the value, and the traceback. The sys module, exposes the current exception in three parallel variables, exc_type , exc_value , and exc_traceback , the sys.exc_info() function returns a tuple of these three parts, and the raise statement has a three-argument form accepting these three parts.
Manipulating exceptions often requires passing these three things in parallel, which can be tedious and error-prone. Additionally, the except statement can only provide access to the value, not the traceback. Adding the __traceback__ attribute to exception values makes all the exception information accessible from a single place. History Raymond Hettinger [1] raised the issue of masked exceptions on Python-Dev in January 2003 and proposed a PyErr_FormatAppend() function that C modules could use to augment the currently active exception with more information.
Brett Cannon [2] brought up chained exceptions again in June 2003, prompting a long discussion. Greg Ewing [3] identified the case of an exception occurring in a finally block during unwinding triggered by an original exception, as distinct from the case of an exception occurring in an except block that is handling the original exception. Greg Ewing [4] and Guido van Rossum [5] , and probably others, have previously mentioned adding a traceback attribute to Exception instances.
This is noted in PEP 3000 . This PEP was motivated by yet another recent Python-Dev reposting of the same ideas [6] [7] . Rationale The Python-Dev discussions revealed interest in exception chaining for two quite different purposes. To handle the unexpected raising of a secondary exception, the exception must be retained implicitly. To support intentional translation of an exception, there must be a way to chain exceptions explicitly.
This PEP addresses both. Several attribute names for chained exceptions have been suggested on Python-Dev [2] , including cause , antecedent , reason , original , chain , chainedexc , xc_chain , excprev , previous and precursor . For an explicitly chained exception, this PEP suggests __cause__ because of its specific meaning. For an implicitly chained exception, this PEP proposes the name __context__ because the intended meaning is more specific than temporal precedence but less specific than causation: an exception occurs in the context of handling another exception.
This PEP suggests names with leading and trailing double-underscores for these three attributes because they are set by the Python VM. Only in very special cases should they be set by normal assignment. This PEP handles exceptions that occur during except blocks and finally blocks in the same way. Reading the traceback makes it clear where the exceptions occurred, so additional mechanisms for distinguishing the two cases would only add unnecessary complexity.
This PEP proposes that the outermost exception object (the one exposed for matching by except clauses) be the most recently raised exception for compatibility with current behaviour. This PEP proposes that tracebacks display the outermost exception last, because this would be consistent with the chronological order of tracebacks (from oldest to most recent frame) and because the actual thrown exception is easier to find on the last line.
To keep things simpler, the C API calls for setting an exception will not automatically set the exception’s __context__ . Guido van Rossum has expressed concerns with making such changes [8] . As for other languages, Java and Ruby both discard the original exception when another exception occurs in a catch/rescue or finally/ensure clause. Perl 5 lacks built-in structured exception handling. For Perl 6, RFC number 88 [9] proposes an exception mechanism that implicitly retains chained exceptions in an array named @@ .
In that RFC, the most recently raised exception is exposed for matching, as in this PEP; also, arbitrary expressions (possibly involving @@ ) can be evaluated for exception matching. Exceptions in C# contain a read-only InnerException property that may point to another exception. Its documentation [10] says that “When an exception X is thrown as a direct result of a previous exception Y, the InnerException property of X should contain a reference to Y.” This property is not set by the VM automatically; rather, all exception constructors take an optional innerException argument to set it explicitly.
The __cause__ attribute fulfills the same purpose as InnerException , but this PEP proposes a new form of raise rather than extending the constructors of all exceptions. C# also provides a GetBaseException method that jumps directly to the end of the InnerException chain; this PEP proposes no analog. The reason all three of these attributes are presented together in one proposal is that the __traceback__ attribute provides convenient access to the traceback on chained exceptions.
Implicit Exception Chaining Here is an example to illustrate the __context__ attribute: def compute ( a , b ): try : a / b except Exception , exc : log ( exc ) def log ( exc ): file = open ( 'logfile.txt' ) # oops, forgot the 'w' print >> file , exc file . close () Calling compute(0, 0) causes a ZeroDivisionError . The compute() function catches this exception and calls log(exc) , but the log() function also raises an exception when it tries to write to a file that wasn’t opened for writing.
In today’s Python, the caller of compute() gets thrown an IOError . The ZeroDivisionError is lost. With the proposed change, the instance of IOError has an additional __context__ attribute that retains the ZeroDivisionError . The following more elaborate example demonstrates the handling of a mixture of finally and except clauses: def main ( filename ): file = open ( filename ) # oops, forgot the 'w' try : try : compute () except Exception , exc : log ( file , exc ) finally : file . clos () # oops, misspelled 'close' def compute (): 1 / 0 def log ( file , exc ): try : print >> file , exc # oops, file is not writable except : display ( exc ) def display ( exc ): print ex # oops, misspelled 'exc' Calling main() with the name of an existing file will trigger four excepti
The rest of this page is on the live site.