【问题标题】:How to get all possible exceptions from a block? [duplicate]如何从块中获取所有可能的异常? [复制]
【发布时间】:2018-06-30 01:19:29
【问题描述】:

有没有办法确定代码块中可能引发的所有可能异常? (例如,一些基于代码块建议捕获某些特定异常而不是仅仅引发该异常的逻辑太通用了。

    try:
        m = check_output(["dd", "--version"]).decode()
        ver_line = m.split('\n')[0]
        ver = ver_line.split(' ')
        if float(ver[2]) >= 8.24:
            logger.info("coreutils version: {}, required >= 8.24".format(ver[2]))
        else:
            logger.warn("coreutils version: {}, required >= 8.24."
                        "Please ensure that the right version is installed".format(ver[2]))
            sys.exit(1)

    except Exception:
        logger.warn("could not determine coreutils version, required >= 8.24")
        return

【问题讨论】:

  • 您可以通过将“except Exception”替换为“except Exception as error”来打印该异常的消息,然后打印错误变量,如果这对您有帮助的话。
  • 根据我的经验,通常情况下我只想捕获来自已知原因的异常(我知道这是“好的”)。如果我想捕获所有可能的异常,您的代码就是这样做的。您是否正在寻找能够通过并识别可能的错误类型及其原因的东西?

标签: python python-3.x


【解决方案1】:

将异常设置为 e,您可以打印异常,无论它是什么 您确定错误使用

type(e) == IndexError

然后你比较它的值

a = ['a', 'b', 1, 3, 4, 5, 6]

for i in range(0, 20):
    try:
        print(int(a[i]))
    except Exception as e:
        if type(e) == IndexError:
            pass
        else:
            print("ERROR",e)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多