How do I prevent exceptions from stopping execution? (global exception handler)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • PyNoob
    New Member
    • Jun 2008
    • 1

    #1

    How do I prevent exceptions from stopping execution? (global exception handler)

    By default, uncaught exceptions stop the execution of python scripts (similar to what bash does when -e us set.)

    I need to change this behavior, so that the user gets informed about the uncaught exception, but the program continues (like +e in bash).

    Reason:
    While a programmer can do his best and wrap almost every function into a try... except... statement, there is always the possibility that one forgets such a wrapping. Also, wrapping every line of code in a try... except... statement adds a lot of bloat to the application.

    Another reason:
    I want to create a GUI application that should display any(!) errors that might occur in a GUI dialog box, rather than "hard crashing" (printing a stack trace and exception to stdout). Simply wrapping the entire main() into a try... except statement would not do the trick because in the case of an error, I could display the error message but I see no apparent way to continue the execution of the GUI app.

    So here is some code to make my question more concrete:

    #!/usr/bin/env python

    import os, sys

    print "One"
    print "Two" + 1
    print "Three"

    # Desired output:
    #
    # One
    # An error occured: cannot concatenate 'str' and 'int' objects -- but we are continuing anyway
    # Three

    # What i do NOT want my code to look like:
    # try... except... try... except...

    # Perhaps something like the following code can help achieve this goal?

    def excepthook(exct ype, value, traceback):
    """Prints only the error message as opposed to the full traceback"""
    print str(value)
    pass

    sys.excepthook = excepthook

    # BUT HOW CAN I MAKE THIS CONTINUE EXECUTION?
Working...