python requests try except

Handling Exceptions in Python Requests using Try Except

Python Requests is a popular library used for making HTTP requests in Python. While making requests, sometimes we may encounter errors such as timeouts, connection errors, and invalid responses. To handle such errors, we can use the try-except block in Python.


Let's say we want to make a request to a website and handle any possible exceptions that may occur:

import requests

url = ''

    response = requests.get(url)
except requests.exceptions.RequestException as err:
    print(f'Request failed: {err}')

In the above example, we are first making a GET request to the specified URL using the requests.get() method. We then use the raise_for_status() method to raise an HTTPError for any unsuccessful HTTP status codes returned by the server.

The code inside the try block may throw various exceptions, such as ConnectionError, Timeout, SSLError, or HTTPError. We catch all of these exceptions using the requests.exceptions.RequestException base class.

If an exception occurs, we print an error message containing the exception message using the print statement. We could also perform other actions or return a custom error message.

Other Exception Handling Techniques:

  • We can catch specific exceptions by using their corresponding exception classes in the except block, such as requests.exceptions.ConnectionError, requests.exceptions.Timeout, etc.
  • We can add a finally block to perform some cleanup or finalization tasks, such as closing a file or releasing a resource.