python requests module try except

Python Requests Module Try Except

If you are working with APIs or web scraping in Python, the requests module is a popular choice for making HTTP requests. However, sometimes the request may fail due to various reasons such as connection problems, server errors, or invalid credentials. In such cases, you can use the "try-except" block to handle the exceptions and prevent your program from crashing.

The try-except block

The try-except block is a Python construct that allows you to catch and handle exceptions that may occur in your program. The syntax for a try-except block is as follows:


try:
    # code that may raise an exception
except ExceptionType:
    # code to handle the exception
    

Here, "ExceptionType" can be any exception class that you want to catch. For example, if you want to catch any exception that may occur in your requests code, you can use the "requests.exceptions.RequestException" class.

Example

Let's say you want to make a GET request to a URL using the requests module. You can use the following code:


import requests

url = 'https://example.com'

response = requests.get(url)

print(response.text)
    

However, if the request fails, your program will crash with an exception. To handle this scenario, you can use the try-except block as follows:


import requests
from requests.exceptions import RequestException

url = 'https://example.com'

try:
    response = requests.get(url)
    response.raise_for_status()
except RequestException as e:
    print('Error: ', e)
else:
    print(response.text)
    

Here, we have wrapped the requests code inside a try block. If the request fails, it will raise a RequestException. We catch this exception in the except block and print the error message. If the request succeeds, we print the response text in the else block.

Multiple exceptions

You can also catch multiple exceptions in a single try-except block by separating them with commas. For example:


try:
    # some code
except (ExceptionType1, ExceptionType2) as e:
    # code to handle the exceptions
    

Here, we catch both ExceptionType1 and ExceptionType2 exceptions.