exception – Catch any error in Python

exception – Catch any error in Python

Using except by itself will catch any exception short of a segfault.

try:
    something()
except:
    fallback()

You might want to handle KeyboardInterrupt separately in case you need to use it to exit your script:

try:
    something()
except KeyboardInterrupt:
    return
except:
    fallback()

Theres a nice list of basic exceptions you can catch here. I also quite like the traceback module for retrieving a call stack from the exception. Try traceback.format_exc() or traceback.print_exc() in an exception handler.

try:
    # do something
except Exception, e:
    # handle it

For Python 3.x:

try:
    # do something
except Exception as e:
    # handle it

exception – Catch any error in Python

You might want also to look at sys.excepthook:

When an exception is raised and uncaught, the interpreter calls
sys.excepthook with three arguments, the exception class, exception
instance, and a traceback object. In an interactive session this
happens just before control is returned to the prompt; in a Python
program this happens just before the program exits. The handling of
such top-level exceptions can be customized by assigning another
three-argument function to sys.excepthook.

Example:

def except_hook(type, value, tback):
    # manage unhandled exception here
    sys.__excepthook__(type, value, tback) # then call the default handler

sys.excepthook = except_hook

Leave a Reply

Your email address will not be published. Required fields are marked *