Connection-related error
A base class for connection-related issues, itself a subclass of `OSError`. More specific exceptions like `BrokenPipeError`, `ConnectionAbortedError`, and `ConnectionRefusedError` inherit from it.
- 1The remote server actively refused the connection (`ConnectionRefusedError`).
- 2The connection was forcibly closed by the remote host (`ConnectionResetError`).
- 3Writing to a pipe or socket where the reading end has been closed (`BrokenPipeError`).
This error (specifically `ConnectionRefusedError`) is triggered when trying to connect to a network port where no process is listening.
import socket
# Connect to a port that is almost certainly not in use
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 9999))
except ConnectionRefusedError as e:
print(f"Caught ConnectionRefusedError: {e}")
expected output
Caught ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
Fix 1
Ensure the server is running and accessible
WHEN You get a `ConnectionRefusedError`.
# This is a conceptual fix, not code. # 1. Check that your server application (e.g., web server, database) is running on the target machine. # 2. Verify that it is listening on the correct IP address and port. # 3. Ensure no firewall is blocking the connection between the client and server.
Why this works
A connection can only be established if a process on the destination machine is actively accepting connections on the specified IP and port.
Fix 2
Implement a retry mechanism with exponential backoff
WHEN The server might be temporarily unavailable (e.g., restarting) and you expect it to be back online shortly.
import requests
import time
for i in range(5):
try:
response = requests.get("http://localhost:9999")
break
except requests.exceptions.ConnectionError:
wait = 2**i # Exponential backoff
print(f"Connection failed, waiting {wait}s to retry...")
time.sleep(wait)
Why this works
By catching the `ConnectionError` and retrying after a progressively longer delay, you can gracefully handle temporary server downtime without overwhelming the server with rapid-fire reconnection attempts.
import socket
s = socket.socket()
s.connect(("localhost", 9999)) # ConnectionRefusedError (subclass)try:
conn = connect_to_service()
except ConnectionRefusedError:
print("Service not running")
except ConnectionResetError:
print("Connection reset by peer")import time
for attempt in range(5):
try:
conn = connect()
break
except ConnectionError:
time.sleep(2 ** attempt)✕ Catching the base `ConnectionError` when you can be more specific
Handling `ConnectionRefusedError` (server not ready) is different from `BrokenPipeError` (client/server disconnected mid-communication). Catching the more specific exception allows for more appropriate recovery logic.
cpython/Objects/exceptions.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev