How to Fix ConnectionError in Python
In this tutorial, you'll learn about How to Fix ConnectionError in Python. We cover key concepts, practical examples, and best practices.
Python raises ConnectionError when a network connection attempt fails due to network-level issues like refused connections or unreachable hosts.
The Wrong Way
import urllib.request
response = urllib.request.urlopen("http://localhost:9999")
print(response.read())
This produces:
Traceback (most recent call last):
File "script.py", line 3, in <module>
response = urllib.request.urlopen("http://localhost:9999")
ConnectionRefusedError: [Errno 111] Connection refused
The Right Way
Wrap network calls in try-except to handle connection failures:
import urllib.request
from urllib.error import URLError
try:
response = urllib.request.urlopen("http://localhost:9999", timeout=5)
print(response.read())
except ConnectionRefusedError:
print("Connection refused -- is the server running?")
except URLError as e:
print(f"URL error: {e.reason}")
Output:
Connection refused -- is the server running?
Step-by-Step Fix
1. Use requests library with timeout
import requests
try:
response = requests.get("http://localhost:9999", timeout=5)
response.raise_for_status()
except requests.ConnectionError:
print("Cannot connect to the server")
except requests.Timeout:
print("Request timed out")
2. Verify the server is running
import socket
def check_port(host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((host, port))
sock.close()
return result == 0
if check_port("localhost", 9999):
print("Server is running")
else:
print("Server is not running on localhost:9999")
3. Retry with exponential backoff
import time
import requests
def connect_with_retry(url, retries=3):
for attempt in range(retries):
try:
return requests.get(url, timeout=5)
except requests.ConnectionError:
if attempt < retries - 1:
time.sleep(2 ** attempt)
else:
raise
return None
Prevention Tips
- Always set timeouts on network requests.
- Use retry logic with exponential backoff for transient errors.
- Check server status before making requests.
- Validate URLs and hostnames before connecting.
- Use connection pooling for repeated connections.
Common Mistakes with connectionerror
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro