March 2019
Beginner
490 pages
12h 40m
English
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.errorfrom urllib.request import urlopentry: 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 Foundstatus 404reason Not Foundurl https://www.ietf.org/rfc/rfc0.txt ...
Read now
Unlock full access