[英]python - handle connection exception (requests.exceptions.ConnectionError)
I have a script that is running fine until it throws a connection exception and stops the whole program.我有一个运行良好的脚本,直到它引发连接异常并停止整个程序。 How can I deal with (ignore) this exception?
我该如何处理(忽略)这个异常? As you can probably tell I have never dealt with this kind of thing in Python before
正如您可能知道的那样,我以前从未在 Python 中处理过这种事情
It sounds to me like you want to implement a try/except block.听起来你想实现一个 try/except 块。 RealPython has a good tutorial on handling exceptions gracefully but the basic structure is as follows:
RealPython 有一个很好的优雅处理异常的教程,但基本结构如下:
try:
# some code that may produce an exception
except: # this will catch any exceptions, which is generally bad practice
# code to execute ONLY if there is an exception
else:
# code to execute ONLY if there is NOT an exception
finally:
# code to run regardless, often used for clean up
Only the try
and except
blocks are necessary;只有
try
和except
块是必需的; the else
and finally
blocks are optional. else
和finally
块是可选的。 As I mentioned above, it is typically bad practice to catch all errors by just using the except keyword.正如我上面提到的,仅使用 except 关键字来捕获所有错误通常是不好的做法。 Instead, you want to catch specific errors like in the following example:
相反,您希望捕获特定错误,如下例所示:
from requests.exceptions import ConnectionError
try:
# some code that may produce an exception
except ConnectionError: # this will only catch ConnectionErrors
# code to execute ONLY if there is a ConnectionError
else:
# code to execute ONLY if there is NOT a ConnectionError
finally:
# code to run regardless, often used for clean up
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.