Catching all exceptions in Python

Matt Joiner picture Matt Joiner · Aug 23, 2011 · Viewed 16.6k times · Source

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.

Answer

mouad picture mouad · Aug 23, 2011
  • except Exception: vs except BaseException::

    The difference between catching Exception and BaseException is that according to the exception hierarchy exception like SystemExit, KeyboardInterrupt and GeneratorExit will not be caught when using except Exception because they inherit directly from BaseException.

  • except: vs except BaseException::

    The difference between this two is mainly in python 2 (AFAIK), and it's only when using an old style class as an Exception to be raised, in this case only expression-less except clause will be able to catch the exception eg.

    class NewStyleException(Exception): pass
    
    try:
       raise NewStyleException
    except BaseException:
       print "Caught"
    
    class OldStyleException: pass
    
    try:
       raise OldStyleException
    except BaseException:
       print "BaseException caught when raising OldStyleException"
    except:
       print "Caught"