Ily*_*rov 4 python exception-handling python-requests
我正在这样做:
import requests
r = requests.get("http://non-existent-domain.test")
Run Code Online (Sandbox Code Playgroud)
并得到
ConnectionError: HTTPConnectionPool(host='non-existent-domain.test', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x10b0170f0>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试这样捕获它:
try:
r = requests.get("http://non-existent-domain.test")
except ConnectionError:
print("ConnectionError")
Run Code Online (Sandbox Code Playgroud)
没什么变化,我还是没有ConnectionError
处理。如何正确捕捉?
那是不同的ConnectionError
。您正在捕获内置的,但是requests
有它自己的。所以这应该是
try:
r = requests.get("http://non-existent-domain.test")
except requests.ConnectionError:
print("ConnectionError")
# Output: ConnectionError
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2085 次 |
最近记录: |