How to tell if an exception has been caught ( from inside theexception )?

Fredrik Lundh fredrik at pythonware.com
Thu Sep 22 09:38:35 EDT 2005


Paul Dale wrote:

> I'm writing an exception that will open a trouble ticket for certain
> events. Things like network failure. I thought I would like to have it
> only open a ticket if the exception is not caught. Is there a way to do
> this inside the Exception? As far as I can see there are only two events
> called on the exception, __init__ and __del__, both of which will be
> called wether or not an exception is caught (right?)
>
> Am I missing something, or is there a way to do this with exceptions?

if you want to trap "uncaught" exceptions, add an except handler to the top
level of your program:

    try:
        main()
    except MySpecialException, v:
        v.open_trouble_ticket()

a less convoluted approach would be do to

    def open_trouble_ticket(exctype, value, traceback):
        ...

    try:
        main()
    except:
        open_trouble_ticket(*sys.exc_info())

or, in recent Python versions,

    import sys

    def open_trouble_ticket(exctype, value, traceback):
        ...

    sys.excepthook = open_trouble_ticket

    main()

</F> 






More information about the Python-list mailing list