python requests exceptions

Python Requests Exceptions

Working with APIs and web services often involves making HTTP requests. Python's requests library is widely used for this purpose. However, sometimes things can go wrong while making a request, and the requests library provides several exceptions to handle these situations.

Timeout Exception

The Timeout exception is raised when a request takes too long to complete. By default, requests do not have a timeout. However, you can set a timeout value using the timeout parameter. For example:


import requests

try:
    response = requests.get('https://www.example.com', timeout=5)
    response.raise_for_status()
except requests.Timeout:
    print('The request timed out')
  

Connection Error Exception

The ConnectionError exception is raised when a connection to the server cannot be established or when a connection is unexpectedly closed. For example:


import requests

try:
    response = requests.get('https://www.example.com')
    response.raise_for_status()
except requests.ConnectionError:
    print('A connection error occurred')
  

HTTP Error Exception

The HTTPError exception is raised when the server returns a non-200 status code. For example:


import requests

try:
    response = requests.get('https://www.example.com/404')
    response.raise_for_status()
except requests.HTTPError as error:
    print(f'An HTTP error occurred: {error}')
  

Request Exception

The RequestException exception is the base class for all requests exceptions. It is raised when an ambiguous exception occurs. For example:


import requests

try:
    response = requests.get('https://www.example.com')
    response.raise_for_status()
except requests.RequestException as error:
    print(f'An error occurred: {error}')
  

Multiple Exceptions

You can handle multiple exceptions using multiple except blocks:


import requests

try:
    response = requests.get('https://www.example.com', timeout=5)
    response.raise_for_status()
except requests.Timeout:
    print('The request timed out')
except requests.ConnectionError:
    print('A connection error occurred')
except requests.HTTPError as error:
    print(f'An HTTP error occurred: {error}')
except requests.RequestException as error:
    print(f'An error occurred: {error}')