ConnectionRefusedError
In Python, ConnectionRefusedError
is a built-in exception that occurs when a connection attempt to a remote server is explicitly refused.
This exception typically happens when the server isn’t running, the server’s firewall is blocking the connection, or the server isn’t listening on the specified port.
As a developer, you might encounter this exception when writing networking code that involves connecting to a server.
ConnectionRefusedError
Occurs When
- Connecting to a server that isn’t running
- Finding that the server’s firewall is blocking the connection
- Connecting to a server that isn’t listening on the specified port
ConnectionRefusedError
Can Be Used When
- Handling network connections in client-server applications
- Implementing retry logic when a connection attempt fails
- Providing user feedback when a connection can’t be established
ConnectionRefusedError
Examples
An example of when the exception appears:
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(("localhost", 9999))
Traceback (most recent call last):
...
ConnectionRefusedError: [Errno 61] Connection refused
An example of how to handle the exception:
>>> import socket
>>> try:
... s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
... s.connect(("localhost", 9999))
... except ConnectionRefusedError:
... print("Connection refused.")
...
Connection refused.
You generally won’t raise ConnectionRefusedError
manually in your code. Instead, you handle it when it occurs naturally as part of socket operations.
Related Resources
Tutorial
Socket Programming in Python (Guide)
In this in-depth tutorial, you'll learn how to build a socket server and client with Python. By the end of this tutorial, you'll understand how to use the main functions and methods in Python's socket module to write your own networked client-server applications.
For additional information on related topics, take a look at the following resources:
- Python's Built-in Exceptions: A Walkthrough With Examples (Tutorial)
- Python's raise: Effectively Raising Exceptions in Your Code (Tutorial)
- Programming Sockets in Python (Course)
- Socket Programming in Python (Quiz)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Using raise for Effective Exceptions (Course)
- Python's raise: Effectively Raising Exceptions in Your Code (Quiz)
By Leodanis Pozo Ramos • Updated May 20, 2025