Search code examples
pythonmultithreadingexceptionpython-3.xcatch-all

Catching all exceptions in Python


In Python, what's the best way to catch "all" exceptions?

except: # do stuff with sys.exc_info()[1]

except BaseException as exc:

except Exception as exc:

The catch may be executing in a thread.

My aim is to log any exception that might be thrown by normal code without masking any special Python exceptions, such as those that indicate process termination etc.

Getting a handle to the exception (such as by the clauses above that contain exc) is also desirable.


Solution

  • If you need to catch all exceptions and do the same stuff for all, I'll suggest you this :

    try:
       #stuff
    except:
       # do some stuff
    

    If you don't want to mask "special" python exceptions, use the Exception base class

    try:
       #stuff
    except Exception:
       # do some stuff
    

    for some exceptions related management, catch them explicitly :

    try:
       #stuff
    except FirstExceptionBaseClassYouWantToCatch as exc:
       # do some stuff
    except SecondExceptionBaseClassYouWantToCatch as exc:
       # do some other stuff based
    except (ThirdExceptionBaseClassYouWantToCatch, FourthExceptionBaseClassYouWantToCatch) as exc:
       # do some other stuff based
    

    The exception hierarchy from the python docs should be a usefull reading.