[Tutor] Exceptions and wotnot
Thu, 21 Feb 2002 00:56:58 +1100
From: "Michael P. Reilly" <firstname.lastname@example.org>
> On Wed, Feb 20, 2002 at 08:46:00PM +0800, Andy W wrote:
> > 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
> > 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.
Ah, the good old feature. Thanks alot for pointing this out! It will
surely save alot of trouble :).
> Some things to know:
> 1. Import traceback before you need it (before the exception occurs).
I didn't even know the module existed. For shame! That's why I looked in
the tutorial instead of lib, but in there I did see something about sys -
just didn't click to go follow it up.
> 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).
Indeed. My program does use some threaded operations, but threaded GUI
operations are the causes of crashes - I learnt my lesson last time. A
game, constructed entirely of tkinter/python code (pygame not given to me as
an option) which crashed all the time. Eventually, after my questions here,
the gracious Tim Peters came to my rescue...if you could call it that.
Basically I needed to rewrite a bunch of my code so that all GUI operations
were handled in the main thread, and only calculations went on in the
auxilary thread. I was lazy not to do it that way regardless, but...lesson
> (You probably don't want to have a thread display a popup to a
> Tkinter window, but there are ways to do that too.)
Yup. Dunno about popping up a window in a thread, but any intensive GUI
interaction between threads seems to cause any system to crash.
> 3. There are a lot of functions in the traceback module, pick the right
> import string, sys, traceback
> def main():
> # 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)
> Using the last_traceback value would get you the wrong info.
Thanks again. I don't mean any harm to Andy W - he still 'showed me the
way' so to speak. I am grateful to you both :)