Last Updated : 12 Jul, 2025
We are given a scenario where we use the Python requests library to make HTTP calls, and we want to check if any error occurred during the request. This can be done using the raise_for_status() method on the response object. For example, if we request a page that doesn't exist, this method will raise an error instead of silently failing. Here's an example:
Python
import requests
res = requests.get('https://example.com/invalid')
res.raise_for_status()
If the URL is invalid or returns a 4xx/5xx status code, it raises an HTTPError.
The raise_for_status() method belongs to the Response object in the requests library. It checks the HTTP status code of the response:
In this example, we make two requests: one to a valid API endpoint and one to a non-existent page. The first request to GitHub succeeds, so raise_for_status() does nothing. The second request fails with a 404 error, and raise_for_status() raises an HTTPError.
Python
import requests
# Valid request
res = requests.get('https://api.github.com/')
res.raise_for_status()
print("Success!")
# Invalid request
res = requests.get('https://www.geeksforgeeks.org/naveen/')
res.raise_for_status()
Output:
Success!
Traceback (most recent call last):
...
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://www.geeksforgeeks.org/naveen/
This approach is helpful during development when you want to catch issues immediately and avoid silent failures.
Example 2: Graceful Error Handling with try-exceptThis example demonstrates how to use raise_for_status() with a try-except block. If an error occurs, it catches and prints a helpful message instead of crashing the program.
Python
import requests
try:
res = requests.get('https://example.com/bad-url')
res.raise_for_status()
except requests.exceptions.HTTPError as e:
print("HTTP error occurred:", e)
except requests.exceptions.RequestException as e:
print("A request error occurred:", e)
Output:
HTTP error occurred: 404 Client Error: Not Found for url: https://example.com/bad-url
This method is best for production code or applications that need to continue running even when a request fails. It allows you to handle errors cleanly and inform the user or log them.
When Should You Use raise_for_status()?Now that we've seen how raise_for_status() works both directly and inside try-except, let’s explore the specific scenarios where this method is most useful.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4