python - 如何创建具有多种原因的 python 异常?

标签 python python-3.x python-2.7 exception

如何引发具有多种原因的 python 异常,类似于 Java 的 addSuppressed()特征?例如,我有多个要尝试的方法列表,如果它们都不起作用,我想引发一个异常,其中包括所有已尝试方法的异常。即:

exceptions = []
for method in methods_to_try:
  try:
    method()
  except Exception as e:
    exceptions.append(e)
if exceptions:
  raise Exception("All methods failed") from exceptions

但是这段代码失败了,因为 raise ... from ... 语句需要一个异常而不是一个列表。 Python 2 或 3 解决方案是可以接受的。必须保留所有回溯和异常消息。

最佳答案

在创建最后一个异常时将异常作为参数传递。

for method in methods_to_try:
    try:
        method()
    except Exception as e:
        exceptions.append(e)
if exceptions:
    raise Exception(*exceptions)

它们将在 args 属性中可用。

关于python - 如何创建具有多种原因的 python 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55048047/

相关文章:

python - 从 python 使用 RotatingFileHandler 时无法获取备份日志文件

python - OpenCV 的 calcOpticalFlowFarneback 的未知输出

python - 从 hdf5 加载组

python-3.x - python选择子集,其中df列值包含数组中的值之一

python - 如何从python中的文本中提取数字?

python - 从 input() 中提取参数

python - 如何在 Anaconda Env 中启动 Visual Studio Code

python - 对象列表的自定义排序

python - Python的交互提示 ">>>"输出到哪里?

python - 如何跟踪从多处理池返回的异步结果