Catch any error in Python

user825286 picture user825286 · Jul 25, 2011 · Viewed 43.1k times · Source

Is it possible to catch any error in Python? I don't care what the specific exceptions will be, because all of them will have the same fallback.

Answer

lunixbochs picture lunixbochs · Jul 25, 2011

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()

There's 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.