In Python, ConnectionError is an exception that is used to indicate connection failures sometimes in socket programs or when a request is made to other servers.
In this tutorial, we are going to explore what is a ConnectionError exception, and how you can handle and resolve this issue with examples. Let’s get started.
ConnectionError Exception – Overview
ConnectionError is an exception that is thrown when a network connection fails. This can happen in many scenarios such as the server is busy, the client’s internet connection is disconnected or the server is down. A properly handled ConnectionError can prevent your program from crashing due to connection failures.
It’s a subclass of RequestsExceptions which can be raised when there are problems with establishing a network connection or sending data.
ConnectionError is raised for all Request and Response instances so it’s important to know how to handle this exception.
Causes of ConnectionError
There are different scenarios in which a ConnectionError exception can be raised, some of them include:
- Incorrect URL
- Wrong connectivity
- Server not responding
- Proxy issue
- Timeout issue
- SSL certificate errors
Now let’s have a look at some examples where we will get to see the cause of ConnectionError exception
Examples
Example 1: Incorrect URL
import requests try: url = 'some_wrong_url' response = requests.get(url) print(response.content) except requests.exceptions.ConnectionError as error: print("Connection Error: ",error)
Output:
Connection Error: HTTPConnectionPool(host='some_wrong_url', port=80): Max retries exceeded with url: / (Caused by NewConnectionError( '<urllib3.connection.HTTPConnection object at 0x7f9b46948828>: Failed to establish a new connection: [Errno -2] Name or service not known',))
As we look at the code, we have the wrong URL given in the URL variable when we make a request for the content, the requests library is throwing a ConnectionError with the message- HTTPConnectionPool(host=’some_wrong_url‘, port=80): Max retries exceeded with url:/ (caused by NewConnectionError). This error message is indicating that the given URL is not accessible or it is not resolving to any IP address.
Example 2: Server Not Responding
import requests try: url = 'https://github.com/downsama/nihss/raw/master/NIHSS.png?raw=true-hello' response = requests.get(url) print(response.content) except requests.exceptions.ConnectionError as error: print("Connection Error: ", error)
Output:
Connection Error: HTTPSConnectionPool(host='github.com', port=443): Max retries exceeded with url: /downsama/nihss/raw/master/NIHSS.png?raw=true-hello (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f9b46919278>: Failed to establish a new connection: [Errno -2] Name or service not known',))
When we make a request for the content of a URL through the request library, the library is throwing a ConnectionError with the message: Max retries exceeded with url: /downsama/nihss/raw/master/NIHSS.png?raw=true-hello. This error message is indicating that the server at github.com is not responding or it has a connectivity issue
Example 3: Proxy Issue
Another cause of Connection Error is Proxy Issue, an example in this scenario is below:
import requests proxies_list = { "http": "http://127.0.0.1:63137", "https": "http://127.0.0.1:63137" } try: url = 'https://github.com' response = requests.get(url, proxies=proxies_list) print(response.content) except requests.exceptions.ProxyError as error: print("Proxy Error: ", error) except requests.exceptions.ConnectionError as error: print("Connection Error: ", error)
Output:
Proxy Error: HTTPSConnectionPool(host='github.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', gaierror(-2, 'Name or service not known')))
In the above code, you can observe that we declared a dictionary with two keys http, and https which contains the proxy details.
Then we made a request to the URL with the defined proxies, and when the connection failed, the error falls into ConnectionError Exception.
How to Handle ConnectionError Exception
Now, you might be wondering how you can handle ConnectionError when there is a failure in establishing the connectivity. We can handle ConnectionError using the try-catch block in Python, as shown in the below code snippet:
try: # Code to connect to the network except requests.exceptions.ConnectionError as error: # Handle the error print(error)
We can handle the ConnectionError by catching and processing the exception using a try…except statement in Python. The key here is to make sure your code isn’t so fragile that it will throw ConnectionError when no actual connection failure has occurred, but rather when it is an expected response.
We should catch and handle the errors that we know could happen rather than allow the program to crash when an unexpected error occurs.
Example 4: ConnectionError Handling
Let’s see ConnectionError handling using try-catch blocks in action:
import requests try: url = 'some_wrong_url' response = requests.get(url) print(response.content) except requests.exceptions.ConnectionError as error: print("Error Encountered: ",error) except requests.exceptions.Timeout as error: print("Timeout Error Encountered: ",error) except requests.exceptions.RequestException as error: print("Something went wrong: ",error)
Output:
Error Encountered: HTTPConnectionPool(host='some_wrong_url', port=80): Max retries exceeded with url: / (Caused by NewConnectionError( '<urllib3.connection.HTTPConnection object at 0x7f9b46948828>: Failed to establish a new connection: [Errno -2] Name or service not known',))
In the above code snippet, we have defined different blocks in which an exception would be caught, and the corresponding message would be printed to the console.
Conclusion
ConnectionError is one of the exceptions raised in Python request library when there is a failure in establishing the connectivity. This can happen due to various reasons, and we have seen examples in which the ConnectionError was raised.
In this tutorial, we have learned how you can handle and resolve these issues using try-catch blocks in Python in the most efficient way to prevent them from crashing. I hope this article helped you. Thanks for reading.