<div dir="ltr"><div><div><div>The issue is in the <a href="https://docs.python.org/3.2/howto/urllib2.html#handling-exceptions">Handling Exeption</a> part and more precisely in the <a href="https://docs.python.org/3.2/howto/urllib2.html#number-2">last example</a>.<br>
<br></div>The order of the exception catching part is false:<br></div>It's like that in the doc :<br>------------------------------<br>from urllib.request import Request, urlopen<br>from urllib.error import URLError<br>
req = Request(someurl)<br>try:<br> response = urlopen(req)<br>except URLError as e:<br> if hasattr(e, 'reason'):<br> print('We failed to reach a server.') # URLError handling<br> print('Reason: ', e.reason)<br>
elif hasattr(e, 'code'):<br> print('The server couldn\'t fulfill the request.') # HTTPError handling<br> print('Error code: ', e.code)<br>else:<br> # everything is fine<br>
------------------------------<br><br></div>and the correct order is :<br>------------------------------<br>from urllib.request import Request, urlopen<br>from urllib.error import URLError<br>req = Request(someurl)<br>try:<br>
response = urlopen(req)<br>except URLError as e:<br> if hasattr(e, 'code'):<br> print('The server couldn\'t fulfill the request.') # HTTPError handling<br> print('Error code: ', e.code)<br>
elif hasattr(e, 'reason'):<br> print('We failed to reach a server.') # URLError handling<br> print('Reason: ', e.reason)<br>else:<br> # everything is fine<br>------------------------------<br>
<div><br></div><div>Because, just as explained over the example (in the doc), if the URLError handling comes first it will also catch the HTTPError.<br><br></div><div>I hope I'm clear enough<br><br></div><div>Have a nice day :-)<br>
</div></div>