Handling exceptions

Status codes should always be checked so that our program can respond appropriately if something goes wrong. The urllib package helps us in checking the status codes by raising an exception if it encounters a problem.

Let's go through how to catch these and handle them usefully. We'll try this following command block. You can find the following code in the urllib_exceptions.py file:

import urllib.error
from urllib.request import urlopen
try:
urlopen('http://www.ietf.org/rfc/rfc0.txt')
except urllib.error.HTTPError as e:
print('Exception', e)
print('status', e.code)
print('reason', e.reason)
print('url', e.url)

The output of the previous script is:

Exception HTTP Error 404: Not Found
status 404
reason Not Found
url https://www.ietf.org/rfc/rfc0.txt

In the previous script, we've requested an rfc0.txt document, which doesn't exist. So the server has returned a 404 status code, and urllib has captured this and raised an HTTPError. You can see that HTTPError provides useful attributes regarding the request. In the preceding example, we obtain the status, reason, and url attributes to get some information about the response.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset