Python requests exception handling

后端 未结 5 1959
梦谈多话
梦谈多话 2020-12-25 09:43

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         


        
5条回答
  •  清酒与你
    2020-12-25 10:30

    Include the requests module using import requests .

    It is always good to implement exception handling. It does not only help to avoid unexpected exit of script but can also help to log errors and info notification. When using Python requests I prefer to catch exceptions like this:

    try:
        res = requests.get(adress,timeout=30)
    except requests.ConnectionError as e:
        print("OOPS!! Connection Error. Make sure you are connected to Internet. Technical Details given below.\n")
        print(str(e))            
        continue
    except requests.Timeout as e:
        print("OOPS!! Timeout Error")
        print(str(e))
        continue
    except requests.RequestException as e:
        print("OOPS!! General Error")
        print(str(e))
        continue
    except KeyboardInterrupt:
        print("Someone closed the program")
    

提交回复
热议问题