0
Follow
4
View

Python requests errors out and I don't know how to catch the error

dhl7777 注册会员
2023-01-26 11:37

Python exception classes hierarchy is:

IOError that is a base class for RequestException have been merged with OSError after python version 3.3:

So as you can see RequestException is not a parent class of TimeoutError exception and can't be used to catch this type of errors:

import requests

try:
    raise TimeoutError('TIMEOUT ERROR')

except requests.exceptions.RequestException as e:
    # catch RequestException type errors that are specific for request library only
    # do something
    print("RequestExceptions will be caught")
 
except TimeoutError as e:
    # catch TimeoutError type errors that has same level in hierarchy as RequestException errors
    # do something
    print("TimeoutErrors will be caught")

except OSError as e:
    # catch all OSError type errors. Little bit wider than previous exceptions
    # do something
    print("TimeoutErrors or RequestExceptions or any other OSErrors will be caught")

except Exception as e:
    # catch any python errors, because all errors in python are children (sub types) for Exception class. Most wider exception type
    # do something
    print("TimeoutErrors or RequestExceptions or OSErrors or any other python errors will be caught")

About the Author

Question Info

Publish Time
2023-01-26 11:37
Update Time
2023-01-26 11:37

Related Question

Python空readlines[重复]

有没有盆友教一下Python bce包怎么用啊

Python怎么用进度条监测程序的完成情况?

计算命令行参数,并删除python中不需要的参数

设置Pipx的路径/目录查找(Python 3.9 / Python 3.10)

Linux无法正确执行Python代码

Python不和机器人读到不同的反应了吗

Python库dl youtube视频与最高分辨率在colab

Python有8个数字加起来直到小于某个数字

为什么我在Python中使用QSqlQuery有这样的性能问题