urllib.error.URLError
PythonERRORNotableNetwork

URL request failed — network or DNS error

Quick Answer

Catch urllib.error.URLError and inspect err.reason to distinguish DNS failures from connection refused or timeouts.

Production Risk

Medium — always set a timeout to avoid indefinite hangs.

What this means

Raised by urllib.request when a URL cannot be fetched due to a network problem, DNS failure, or connection refused. The reason attribute holds the underlying OS error or socket exception.

Why it happens
  1. 1DNS resolution failed for the hostname
  2. 2Connection refused — no server listening on that port
  3. 3No route to host / network unreachable

Fix

Catch and inspect reason

Catch and inspect reason
import urllib.request
import urllib.error

try:
    with urllib.request.urlopen('https://example.com', timeout=10) as resp:
        data = resp.read()
except urllib.error.HTTPError as e:
    print(f'HTTP {e.code}: {e.reason}')
except urllib.error.URLError as e:
    print(f'Network error: {e.reason}')

Why this works

HTTPError (a subclass of URLError) covers HTTP 4xx/5xx responses; URLError covers lower-level failures. Catch HTTPError first.

Code examples
Triggerpython
import urllib.request, urllib.error
try:
    urllib.request.urlopen('http://not.a.real.host')
except urllib.error.URLError as e:
    print(e.reason)  # [Errno -2] Name or service not known
Timeout handlingpython
import socket
try:
    urllib.request.urlopen(url, timeout=5)
except urllib.error.URLError as e:
    if isinstance(e.reason, socket.timeout):
        print('Request timed out')
Sources

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors