Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to catch multiple types of exceptions and then print the exact type that occurred?

This is the closest answer I could find on catching multiple exceptions (the correct way), when after a miracle of acquiescence the interpreter allowed the following snippet:

try:
    x = "5" + 3
except NameError and TypeError as e:
    print e

The docs would provide this snippet as well, but nothing like the former:

... except (RuntimeError, TypeError, NameError):
...     pass

So it would be nice to have a second opinion, but my question really comes down to this:

  • How can I not only print the message, but insert at the beginning of the print statement the exact type of error raised. For example I would prefer the first snippet to respond by printing this instead: TypeError: cannot concatenate 'str' and 'int' objects

I feel like it probably is not possible, or easy, given that the interpreter lists only args and message as members of NameError but perhaps that is simply incomplete.

I have tried this myself, but it no longer excepts the errors (I might be misunderstanding isinstance):

try:
    x = "5" + 3
except (NameError, TypeError) as e:
    if isinstance(e, NameError):
        print "NameError: " + e
    elif isinstance(e, TypeError):
        print "TypeError: " + e
    else:
        print e
like image 763
Leonardo Avatar asked Nov 30 '22 03:11

Leonardo


1 Answers

You can catch the errors individually. See this link for more examples: http://docs.python.org/2/tutorial/errors.html#handling-exceptions

Something like the following:

try:
    x = "5" + 3
except TypeError as e:
    print "This is a TypeError"
    print e
except NameError as e:
    print "This is a NameError"
    print e
like image 75
JRP Avatar answered Dec 04 '22 11:12

JRP