python: How do I know what type of exception occurred? python: How do I know what type of exception occurred? python python

python: How do I know what type of exception occurred?


The other answers all point out that you should not catch generic exceptions, but no one seems to want to tell you why, which is essential to understanding when you can break the "rule". Here is an explanation. Basically, it's so that you don't hide:

So as long as you take care to do none of those things, it's OK to catch the generic exception. For instance, you could provide information about the exception to the user another way, like:

  • Present exceptions as dialogs in a GUI
  • Transfer exceptions from a worker thread or process to the controlling thread or process in a multithreading or multiprocessing application

So how to catch the generic exception? There are several ways. If you just want the exception object, do it like this:

try:    someFunction()except Exception as ex:    template = "An exception of type {0} occurred. Arguments:\n{1!r}"    message = template.format(type(ex).__name__, ex.args)    print message

Make sure message is brought to the attention of the user in a hard-to-miss way! Printing it, as shown above, may not be enough if the message is buried in lots of other messages. Failing to get the users attention is tantamount to swallowing all exceptions, and if there's one impression you should have come away with after reading the answers on this page, it's that this is not a good thing. Ending the except block with a raise statement will remedy the problem by transparently reraising the exception that was caught.

The difference between the above and using just except: without any argument is twofold:

  • A bare except: doesn't give you the exception object to inspect
  • The exceptions SystemExit, KeyboardInterrupt and GeneratorExit aren't caught by the above code, which is generally what you want. See the exception hierarchy.

If you also want the same stacktrace you get if you do not catch the exception, you can get that like this (still inside the except clause):

import tracebackprint traceback.format_exc()

If you use the logging module, you can print the exception to the log (along with a message) like this:

import logginglog = logging.getLogger()log.exception("Message for you, sir!")

If you want to dig deeper and examine the stack, look at variables etc., use the post_mortem function of the pdb module inside the except block:

import pdbpdb.post_mortem()

I've found this last method to be invaluable when hunting down bugs.


Get the name of the class that exception object belongs:

e.__class__.__name__

and using print_exc() function will also print stack trace which is essential info for any error message.

Like this:

from traceback import print_excclass CustomException(Exception): passtry:    raise CustomException("hi")except Exception, e:    print 'type is:', e.__class__.__name__    print_exc()    # print "exception happened!"

You will get output like this:

type is: CustomExceptionTraceback (most recent call last):  File "exc.py", line 7, in <module>    raise CustomException("hi")CustomException: hi

And after print and analysis, the code can decide not to handle exception and just execute raise:

from traceback import print_excclass CustomException(Exception): passdef calculate():    raise CustomException("hi")try:    calculate()except Exception, e:    if e.__class__ == CustomException:        print 'special case of', e.__class__.__name__, 'not interfering'        raise    print "handling exception"

Output:

special case of CustomException not interfering

And interpreter prints exception:

Traceback (most recent call last):  File "test.py", line 9, in <module>    calculate()  File "test.py", line 6, in calculate    raise CustomException("hi")__main__.CustomException: hi

After raise original exception continues to propagate further up the call stack. (Beware of possible pitfall) If you raise new exception it caries new (shorter) stack trace.

from traceback import print_excclass CustomException(Exception): passdef calculate():    raise CustomException("hi")try:    calculate()except Exception, e:    if e.__class__ == CustomException:        print 'special case of', e.__class__.__name__, 'not interfering'        #raise CustomException(e.message)        raise e    print "handling exception"

Output:

special case of CustomException not interferingTraceback (most recent call last):  File "test.py", line 13, in <module>    raise CustomException(e.message)__main__.CustomException: hi    

Notice how traceback does not include calculate() function from line 9 which is the origin of original exception e.


You usually should not catch all possible exceptions with try: ... except as this is overly broad. Just catch those that are expected to happen for whatever reason. If you really must, for example if you want to find out more about some problem while debugging, you should do

try:    ...except Exception as ex:    print ex # do whatever you want for debugging.    raise    # re-raise exception.