Python requests exception handling

user1159798 picture user1159798 · Jan 29, 2012 · Viewed 71.1k times · Source

How to handle exceptions with python library requests? For example how to check is PC connected to internet?

When I try

try:
    requests.get('http://www.google.com')
except ConnectionError:
    # handle the exception

it gives me error name ConnectionError is not defined

Answer

kindall picture kindall · Jan 29, 2012

Assuming you did import requests, you want requests.ConnectionError. ConnectionError is an exception defined by requests. See the API documentation here.

Thus the code should be :

try:
   requests.get('http://www.google.com')
except requests.ConnectionError:
   # handle the exception