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