[Tutor] exception question

Michael Janssen Janssen at rz.uni-frankfurt.de
Wed Apr 28 11:29:12 EDT 2004


On Wed, 28 Apr 2004, Danny Yoo wrote:

> [Dave]
> > My problem is I do not know what the exception error will be. I have a
> > script that will run 247, If an error occurs I want it to e-mail me with
> > the exception error that caused the crash.

> We can get a better stack trace out of the error by using the 'traceback'
> module:
>
>     http://www.python.org/doc/lib/module-traceback.html
>
> So we can probably just trap all "Exception" things, and then use
> traceback to extract more specific information out of the exception.

The traceback-module is the way to do it. Otherwise one will lose all this
"line XX, in foo" information. Since traceback is somewhat complicated
(too much slightly different functions to choose from) I feel like it's
okey, when I post a more or less complete solution.

Assuming you have done your best catching possible errors but you can't be
shure which errors else might show up. The programm is running
automatically or via web, so the printed traceback isn't of that much
help.

Then you put your "main" function (i.e. the function that contains all of
your programm - it's allways good to organize your scripts that way)
within a catchall try-except clause:


if __name__ == "__main__":
    try: main()
    except:
        import traceback, sys
        tb_list = traceback.format_exception(*sys.exc_info())
        body = "Script: %s\n" % sys.argv[0]
        body += ''.join(tb_list)
        mail(body, subject="Script Error", addr="Your address")
        # give it back to console in case somebody is watching
	raise


Explanations:

'if __name__ == "__main__"' is just a ward against running the code when
*importing* the file as a module. It's nice to have when you ever want to
import the script (to reuse its tricky functions). Has nothing to do with
our topic ;-)

"sys.exc_info()": this is where the traceback-object comes from. There is
a warning on http://www.python.org/doc/lib/module-sys.html about problems
with garbage collection. Nevertheless above code should be save (at least
because the programm will terminate soon ;-).

"*sys.exc_info()": sys.exc_info returns a tuple. "*" unfolds the tuple as
arguments to format_exception. This special syntax is described in:
http://docs.python.org/tut/  Section 4.7.4

traceback.format_exception: from all those functions from the
traceback-module this seems proper to me.

"mail": I hope you got your own mail-function? Use smtplib.


The result looks very much like a traceback as written to console. Adding
the hostname into the mail might be a good idea (with socket.gethostname).


Michael



More information about the Tutor mailing list