[Tutor] Exceptions and wotnot
Michael P. Reilly
arcege@speakeasy.net
Wed, 20 Feb 2002 08:29:08 -0500
On Wed, Feb 20, 2002 at 08:46:00PM +0800, Andy W wrote:
> > But it's not really what I want. Surely there must be some way of
> getting
> > the traceback, out of the except Excpeption: construct. I dir()ed the
>
> The "sys" module has a reference to the last traceback, strangely enough
> called "last_traceback" ;)
> You might also want to look at the "traceback" module, as it does some work
> for you.
Actually, last_traceback is the previous traceback, not the current one.
If you put your call in a try-expect: statement, then it would be in
exc_traceback. Because of a "feature" of the interactive interpreter,
the exc_* values get put into last_* at the end of the executed statement.
Some things to know:
1. Import traceback before you need it (before the exception occurs).
2. If you are using threads, use sys.exc_info(). There are thread
specific exceptions and sys.exc_info will get those for you. The
sys.exc_* values will be of either the main thread or last exception
(I can't remember which, and the behavior is undefined anyway).
(You probably don't want to have a thread display a popup to a
Tkinter window, but there are ways to do that too.)
3. There are a lot of functions in the traceback module, pick the right
one.
###
import string, sys, traceback
...
def main():
try:
...
exception:
# display the usual Python exception output, but to a window
exc, val, tb = sys.exc_info()
formatted_lines = traceback.format_exception(exc, val, tb)
exc_output = string.join(formatted_lines)
popup(exc_output)
###
Using the last_traceback value would get you the wrong info.
-Arcege