raise with no argument

When you raise without arguments, the interpreter looks for the last exception raised and handled. It then acts the same as if you used raise with the most recent exception type, value and traceback.

This is stored in the interpreter state for the current thread, and the same information can be retrieved using sys.exc_info(). By ‘handled’ I mean that an except clause caught the exception. Quoting the try statement documentation:

Before an except clause’s suite is executed, details about the exception are assigned to three variables in the sys module: sys.exc_type receives the object identifying the exception; sys.exc_value receives the exception’s parameter; sys.exc_traceback receives a traceback object (see section The standard type hierarchy identifying the point in the program where the exception occurred. These details are also available through the sys.exc_info() function, which returns a tuple (exc_type, exc_value, exc_traceback).

See the implemenation notes in the Python evaluation loop (C code), specifically:

The second
bullet was for backwards compatibility: it was (and is) common to
have a function that is called when an exception is caught, and to
have that function access the caught exception via sys.exc_ZZZ.
(Example: traceback.print_exc()).

The traceback reflects how you came to the re-raise accurately. It is the current stack (line 10 calling f(), line 5 calling g()) plus the original location of the exception raised: line 3.

Leave a Comment