Python

Urllib.Error

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:

    1. 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.
    2. 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.
    3. 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.request
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:

URL Error: urlopen error [Errno 11001] getaddrinfo failed

 

Example 2: HTTPError Exception

In the following example, we illustrate how to use the urllb.error module to handle the HTTPError exceptions:

import urllib.request
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:

HTTP Error 403: Forbidden

 

Conclusion

In this post, we discussed how to use the urllib.error module to handle the URLError and HTTPError exceptions.

Happy coding!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list