Lingua-e
← Errors
Python

ConnectionError: What It Means and How to Fix It

Error reference

ConnectionError

Language

Python

Severity

Medium

When it happens

A ConnectionError is raised in Python when a network operation fails to establish or maintain a connection.

Potential fixes

Verify the target service is running and reachable (try curl or ping). Always set a timeout when making network requests to avoid hanging indefinitely. Wrap network calls in try/except and implement a retry strategy with exponential backoff for transient failures.

Related errors

Deep dive

A ConnectionError is raised in Python when a network operation fails to establish or maintain a connection. In the standard library it is a base class for network-related OSError subclasses. The requests library re-uses this name for HTTP connection failures.

Why it happens

  • The target server is not running or is not reachable at the specified host and port.
  • A firewall or network policy is blocking the connection.
  • The URL has a typo, wrong port, or incorrect protocol (http vs https).
  • The connection was established but dropped unexpectedly mid-request due to a timeout or server restart.

Potential fixes

Verify the target service is running and reachable (try curl or ping). Always set a timeout when making network requests to avoid hanging indefinitely. Wrap network calls in try/except and implement a retry strategy with exponential backoff for transient failures.

Examples

Python

Code that triggers the error

import requests

response = requests.get("http://localhost:8080/api/health")
print(response.status_code)

Error output

Traceback (most recent call last):
  ...
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8080):
Max retries exceeded with url: /api/health
(Caused by NewConnectionError: Failed to establish a new connection:
[Errno 111] Connection refused)

Fixed code

import requests
from requests.exceptions import ConnectionError as RequestsConnectionError

try:
    response = requests.get("http://localhost:8080/api/health", timeout=5)
    print(response.status_code)
except RequestsConnectionError:
    print("Service is unavailable. Check that it is running.")

Practice in English

How would you explain a ConnectionError to a fellow dev? Choose the right phrase:

"I hit an error...

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free