Skip to content

ERROR HANDLING - URLError and HTTPError

Python
#!/usr/bin/env python3
"""ERROR HANDLING - URLError and HTTPError"""
import urllib.request
import urllib.error
print("Error Handling:")
urls = [
    "http://httpbin.org/status/200",
    "http://httpbin.org/status/404",
    "http://invalid-url-that-does-not-exist.com"
]
for url in urls:
    print(f"\n  Testing: {url}")
    try:
        with urllib.request.urlopen(url, timeout=5) as response:
            print(f"    Success: {response.status}")
    except urllib.error.HTTPError as e:
        print(f"    HTTPError: {e.code} {e.reason}")
    except urllib.error.URLError as e:
        print(f"    URLError: {e.reason}")
    except Exception as e:
        print(f"    Error: {e}")