Search code examples
pythonerrnotry-except

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?


Solution

  • 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'>