我怎么能写一个尝试/except块捕获所有异常?
当前回答
try:
whatever()
except:
# this will catch any exception or error
值得一提的是,这不是正确的Python编码。这也将捕获您可能不想捕获的许多错误。
其他回答
有多种方法可以做到这一点,特别是在Python 3.0及以上版本中
方法1
这是一种简单的方法,但不推荐使用,因为你不知道到底是哪行代码引发了异常:
def bad_method():
try:
sqrt = 0**-1
except Exception as e:
print(e)
bad_method()
方法2
推荐使用这种方法,因为它提供了关于每个异常的更多细节。它包括:
代码的行号 文件名称 更详细地描述实际错误
唯一的缺点是需要导入tracback。
import traceback
def bad_method():
try:
sqrt = 0**-1
except Exception:
print(traceback.print_exc())
bad_method()
我刚刚发现了在Python 2.7中测试if异常名称的小技巧。有时我在代码中处理了特定的异常,所以我需要一个测试,看看这个名字是否在处理的异常列表中。
try:
raise IndexError #as test error
except Exception as e:
excepName = type(e).__name__ # returns the name of the exception
要捕获所有可能的异常,请捕获BaseException。它位于Exception层次结构的顶部:
Python 3: https://docs.python.org/3.10/library/exceptions.html#exception-hierarchy
Python 2.7: https://docs.python.org/2.7/library/exceptions.html#exception-hierarchy
try:
something()
except BaseException as error:
print('An exception occurred: {}'.format(error))
但正如其他人提到的,你通常不需要这个,只有在非常特定的情况下。
我添加了奖金方法,可以捕捉异常与完整的回溯,这可以帮助您了解更多的错误。
Python 3
import traceback
try:
# your code goes here
except Exception as e:
print(e)
traceback.print_exc()
首先,有些异常是您希望它们破坏您的代码的(因为当这个错误发生时,您的代码无论如何都不能正常工作!),还有一些异常是您希望以静默/平滑的方式捕获的。试着求微分。您可能不想捕获所有的异常!
其次,不必捕获所有内容,您可以花时间查看流程的日志。假设您正在获得一个不同的/第三方异常,例如来自像GCP这样的云服务提供商。在日志中,您可以找到正在获得的异常。然后,你可以这样做:
from google.api_core.exceptions import ServiceUnavailable, RetryError
for i in range(10):
try:
print("do something")
except ValueError:
print("I know this might happen for now at times! skipping this and continuing with my loop"
except ServiceUnavailable:
print("our connection to a service (e.g. logging) of gcp has failed")
print("initializing the cloud logger again and try continuing ...")
except RetryError:
print("gcp connection retry failed. breaking the loop. try again later!)
break
对于其余的(可能发生或不可能发生的错误),我为代码在遇到意外异常时崩溃留下了空间!这样我就可以理解发生了什么,并通过捕获边缘情况来改进我的代码。
如果你想让它永远不会因为某些原因崩溃,例如,如果它是嵌入在远程硬件中的代码,你不容易访问,你可以在最后添加一个通用的异常捕获器:
except Exception as e:
print(f"something went wrong! - {e}")
您还可以在这里查看Python 3的异常层次结构。Exception和BaseException的区别在于,Exception不会捕获SystemExit, KeyboardInterrupt或GeneratorExit
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录