handling exceptions

Colin Brown cbrown at metservice.com
Thu Sep 19 01:50:31 EDT 2002


> being new to python, I have a question about handling exceptions. I
> want to catch an exception which is raised from a module not written
> by me, and display a messagebox with the message of the exception
> rather than halting the program. The problem is: how can I access the
> message string of the exception?

Hi Karsten

I came across the same problem some time ago when I wanted to write daemon
errors into day-based logfiles and wrote myself the module Excepts.py below:

--[Excepts.py]----------------------------------
# Return Exception errors as strings
import sys, traceback

def error():
    tb =
traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info(
)[2])
    return tb[len(tb)-1].replace('\n','')

def errorstack():
    return
''.join(traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.e
xc_info()[2]))
-------------------------------------------------

example usage:
import Excepts
try:
    functional_code()
except:
    oneliner = Excepts.error()
    log(oneliner)

errorstack returns the full stack if you want that.

Hope this helps.

Colin Brown
PyNZ






More information about the Python-list mailing list