0

I am quite newby into dealing with exceptions in python.

Particularly I would like to create an exception when:

URLError: <urlopen error [Errno 11001] getaddrinfo failed>`

and another one when:

HTTPError: HTTP Error 404: Not Found

If i am right it shall be in both cases a :

except IOError:

however I would like to carry out one code when one error arises and a different code when the other error arises,

How could I differentiate these 2 exceptions?

Thank you

JamesHudson81
  • 2,215
  • 4
  • 23
  • 42

1 Answers1

1

You can set several exception handlers for each type of exception you want to handle, like this:

import urllib2

(...)

try:
    (... your code ...)
except urllib2.HTTPError, e:
    (... handle HTTPError ...)
except urllib2.URLError, e:
    (... handle URLError ...)

Note that this will handle ONLY HTTPError and URLError, any other kind of exception won't be handled. You can add a final except Exception, e: to handle anything else, although this is discouraged as correctly pointed out in the comments.

Obviously replace evrything that's in parenthesis () with your code.

AArias
  • 2,558
  • 3
  • 26
  • 36
  • 1
    Correct, but I suggest to mention that handling generic exception is not a good practice in Python. Cf https://stackoverflow.com/questions/4990718/python-about-catching-any-exception – Pintun Jun 13 '17 at 09:10
  • Agreed, that's why I didn't put it in the main code example block. Will update the answer to note this, thank you. – AArias Jun 13 '17 at 09:12