Catching a traceback

Michael Geary Mike at DeleteThis.Geary.com
Mon Jun 7 23:54:23 EDT 2004


EAS <eriksp at attbi.nospam.com> wrote:
> I'm wondering if there is any way to keep a program running
> when it runs into an error (using the 'try' structure) and print
> the traceback to the screen?

Here's an example of something I did that was similar to what it sounds like
you're looking for. I was writing a Windows application using native Win32
calls, and I wanted to catch any errors and display them in a message box
instead of to the console (because there was no console). In this case, I
just let the program terminate after the message box, but you can take it
from there.

In this example, I've replaced the original main() function with one that
always raises an error:

import traceback, win32ui

def main():
    print unknown

class TraceLog:
    def __init__( self ):
        self.text = ''

    def write( self, text ):
        self.text += text

try:
    main()
except:
    log = TraceLog()
    traceback.print_exc( file=log )
    win32ui.MessageBox( log.text, 'Error' )

-Mike





More information about the Python-list mailing list