Mastering Python HTTP Error Handling: URLError and HTTPError Explained
The article explains how Python's urllib2 raises URLError and HTTPError, details their causes and attributes, and presents two practical approaches for catching and processing these HTTP exceptions to build more robust networked applications.
This article discusses handling HTTP-related exceptions in Python using urllib2, focusing on URLError and HTTPError .
1. URLError
URLError occurs when there is no network connection or the target server cannot be reached. The exception includes a reason attribute, which is a tuple containing an error number and a message (e.g., [Errno 11001] getaddrinfo failed ).
2. HTTPError
HTTPError is a subclass of URLError and is raised for HTTP responses with error status codes (e.g., 404, 403, 401). Each HTTP response carries a numeric status code; codes 200–299 indicate success, while 400–599 indicate various client or server errors. The code attribute of an HTTPError instance holds the numeric error code.
Typical error codes include:
200 – Success
201 – Resource created
202 – Accepted, processing pending
204 – No content
301 – Permanent redirect
302 – Temporary redirect
400 – Bad request
401 – Unauthorized
403 – Forbidden
404 – Not found
5XX – Server error
3. Wrapping Exceptions
Two main strategies are recommended for handling these exceptions.
First approach
Create a script (e.g., urllib2_test08.py) that wraps the request in a try block, catching HTTPError first, then URLError. This order is crucial because HTTPError is a subclass of URLError and would be caught by the latter if placed first.
Second approach
Another script (e.g., urllib2_test09.py) demonstrates a different handling pattern, also catching HTTPError before URLError to ensure proper processing of HTTP-specific errors.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
