Skip to content

Instantly share code, notes, and snippets.

@ocaoimh
Last active June 23, 2023 16:37
Show Gist options
  • Save ocaoimh/4b5925d1b3097f9c95c3d1d15c7d960e to your computer and use it in GitHub Desktop.
Save ocaoimh/4b5925d1b3097f9c95c3d1d15c7d960e to your computer and use it in GitHub Desktop.
try_except.py
from requests import codes # the code names from requests
from http.client import responses #it lets you look up the response
try:
r = requests.get('https://www.abc.net.au/triplej/hottest100/22/1-100', timeout=1)
r.raise_for_status() # returns an HTTPError object if an error has occurred during the process
except requests.exceptions.HTTPError as errh: # explains the errror
print("HTTP Error")
print(errh.args[0]) # look up the 1st argument from HTTPError
else:
status_code = r.status_code # looks up the status code
status_name = responses[status_code] # looks up the http.client import responses
if status_name:
print("Response Code:", status_code)
print("Status Name:", status_name)
else:
print("Response Code:", status_code)
# source: https://www.geeksforgeeks.org/exception-handling-of-python-requests-module/
# source: https://www.w3schools.com/python/python_try_except.asp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment