In this short post, we will discuss about the urllib.error module that defines the exception classes from the urllib.request module.
The module supports the following exceptions:
- URLError – This type of exception is raised when fetching a specific resource. The function provides a reason property which holds the detailed information about the cause of the error.
- HTTPError – This type of exception is raised in the encounter of exotic HTTP errors such as auth. Similarly, the function supports a code, reason, and headers properties that return the HTTP status code, explanation of the error, and the HTTP response headers for the request, respectively.
- ContentTooShortError – This exception is raised if the returned data is less than the expected amount. The data length is defined in the Content-Length header.
Example 1: URLError Exception
The following example code shows how to use the errors raised in the errors module:
import urllib.parse
try:
r = urllib.request.urlopen("https://geekbits.io")
print(r)
except Exception as e:
print(str(e)
Keep in mind that the URLError is a subclass of OSError. Therefore, if we run the previous code without internet connectivity, it should return a URLError as follows:
Example 2: HTTPError Exception
In the following example, we illustrate how to use the urllb.error module to handle the HTTPError exceptions:
import urllib.parse
try:
r = urllib.request.urlopen("https://httpstat.us/403")
print(r)
except Exception as e:
print(str(e))
Running the previous code should return a HTTPError exception as the request encounters a 403 status code.
The resulting output is as follows:
Conclusion
In this post, we discussed how to use the urllib.error module to handle the URLError and HTTPError exceptions.
Happy coding!