Skip to content

How to Handle Python requests.exceptions (ConnectionError, Timeout)

DodaTech 2 min read

In this tutorial, you'll learn about How to Handle Python requests.exceptions (ConnectionError, Timeout). We cover key concepts, practical examples, and best practices.

The Problem

Your Python script using the requests library crashes with requests.exceptions.ConnectionError or requests.exceptions.Timeout when a server is unreachable, DNS fails, or the request takes too long. These exceptions halt execution unless caught, making your application fragile.

Quick Fix

Catch ConnectionError and Timeout with try/except

python3 -c "
import requests
from requests.exceptions import ConnectionError, Timeout

try:
    resp = requests.get('https://nonexistent.example.com', timeout=5)
    print(resp.status_code)
except ConnectionError:
    print('Connection failed — server unreachable')
except Timeout:
    print('Request timed out')
"
# Connection failed — server unreachable

Always catch specific exceptions so your program can degrade gracefully instead of crashing. Handling each exception type separately lets you log meaningful diagnostics and decide whether to retry or abort.

Set Reasonable Timeouts on Every Request

python3 -c "
import requests
try:
    resp = requests.get('https://httpbin.org/delay/10', timeout=(3, 10))
    print(resp.status_code)
except requests.exceptions.Timeout:
    print('Request timed out after 3s connect / 10s read')
"
# Request timed out after 3s connect / 10s read

Pass a tuple (connect_timeout, read_timeout) to control how long to wait for each phase separately. The first value limits the connection establishment time, while the second limits the time between receiving data bytes.

Add Automatic Retries with urllib3 Retry

python3 -c "
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

session = requests.Session()
retries = Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503])
adapter = HTTPAdapter(max_retries=retries)
session.mount('https://', adapter)

try:
    resp = session.get('https://httpbin.org/status/500', timeout=5)
    print(resp.status_code)
except requests.exceptions.RetryError:
    print('All retries exhausted')
"
# All retries exhausted

Mount a retry adapter on the session to automatically retry on transient failures with exponential backoff between attempts.

Verify Your Python Environment

python3 --version
# Python 3.10.12
pip list | grep requests
# requests            2.31.0

Check your Python version and installed packages before debugging. Many errors are caused by version mismatches between development and production environments. Using a virtual environment with pinned dependencies prevents these surprises.

Additional Troubleshooting

# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"

If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.

Use Session Context Managers

python3 -c "
import requests
with requests.Session() as session:
    resp = session.get('https://example.com', timeout=5)
    print(resp.status_code)
"
# 200

Using a Session as a context manager ensures connections are properly released even when exceptions occur. This prevents resource leaks that can lead to connection pool exhaustion and subsequent errors.

Prevention

  • Always pass a timeout argument to every requests.get(), post(), etc.
  • Use try/except blocks around all network calls with specific exception handlers
  • Use a requests.Session with retry adapters for production code to handle transient failures
  • Set environment variables REQUESTS_CA_BUNDLE when behind a corporate proxy

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro