try:
r = requests.get(url, params={'s': thing})
except requests.exceptions.RequestException as e: # This is the correct syntax
print e
sys.exit(1)
或者你可以单独抓到他们,做不同的事情。
try:
r = requests.get(url, params={'s': thing})
except requests.exceptions.Timeout:
# Maybe set up for a retry, or continue in a retry loop
except requests.exceptions.TooManyRedirects:
# Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
print e
sys.exit(1)
If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call Response.raise_for_status. That will raise an HTTPError, if the response was an http error.
例如:
try:
r = requests.get('http://www.google.com/nothere')
r.raise_for_status()
except requests.exceptions.HTTPError as err:
print err
sys.exit(1)
将打印:
404 Client Error: Not Found for url: http://www.google.com/nothere
异常对象还包含原始响应
e.response
,如果需要在服务器的响应中看到错误体,这可能很有用。例如:看看请求exception docs。简而言之:
为了回答你的问题,你所展示的将不会覆盖你所有的基础。您将只捕获与连接相关的错误,而不会捕获超时的错误。
捕获异常时的操作实际上取决于脚本/程序的设计。可以离开吗?你能继续再试一次吗?如果错误是灾难性的,并且您不能继续,那么可以调用
sys.exit()
。您可以捕获基类异常,它将处理所有情况:
或者你可以单独抓到他们,做不同的事情。
正如Christian所指出的:
例如:
将打印:
另一个需要明确的建议。似乎最好是从一堆错误中从一个特定的到另一个通用的,以得到想要捕获的错误,这样特定的错误就不会被通用的错误所掩盖。
对
相关问题 更多 >
编程相关推荐