Tom
Tom

Reputation: 332

Printing Exception type in Python using Errno

I currently have code of the format

try:
    ....
except(HTTPError, URLError, socket.error) as e:
    print "error({0}):{1}".format(e.errno, e.strerror)
continue

But want to know which of the three triggered the exception. Is there a way to do this in python?

Upvotes: 1

Views: 3911

Answers (3)

Sean Azlin
Sean Azlin

Reputation: 916

Try using e.__class__.__name__. It'll return values like "ValueError" or "TypeError".

You could also just use e.__class__, which gives you values like <type 'exceptions.TypeError'>

Upvotes: 2

Air
Air

Reputation: 8615

If it's important for you to react differently then you should catch them individually:

try:
    do_something()
except HTTPError:
    handle_HTTPError()
except URLError:
    handle_URLError()
except socket.error:
    handle socketerror()

But if you only mean that you want to display or log the error type along with its arguments, you should be using the repr of the error instead of trying to format it yourself. For example:

>>> try:
...     raise IOError(911, "Ouch!")
... except IOError as e:
...     print "error({0}):{1}".format(e.errno, e.strerror)
...     print repr(e)
...
error(911):Ouch!
IOError(911, 'Ouch!')

In terms of the information displayed, there's very little difference between the printed string you put together and just going with the repr. If you really want a "pretty" message to print or log, you can manipulate the string to your heart's content, but type(e) won't save you any effort, it's not intended for display/logging:

>>> type(e)
<type 'exceptions.IOError'>

Upvotes: 1

Adrian Stoll
Adrian Stoll

Reputation: 31

def exception():
    try:
        //code that could raise a ValueError or TypeError
    except ValueError as e:
        print "ValueError"
    except TypeError as e:
        print "TypeError"

Just add more except blocks, each with code specific the a given exception.

Upvotes: 0

Related Questions