【问题标题】:Try + Except only catches certain exceptionsTry + except 只捕获某些异常
【发布时间】:2020-06-16 17:09:37
【问题描述】:

TL;DR:为什么我的异常只在某些情况下触发,尽管它是相同的错误?

代码成功捕获了带有全数字参数的 NameError。因此,如果有人错误地输入了数字而不是运算符,它会给他们正确的异常错误消息。但是,我的代码无法捕获其他异常,我不确定为什么。

例如:

打印(better_calc(5, 5, 5))

这将返回所需的异常消息

5 5 5 = 错误:名称错误。请检查您的输入

但是,它不会捕获其他错误。相反,它会终止程序。 例如,

打印(better_calc(5, g, 5))

这会返回 ''NameError: name 'g' is not defined'',不会触发异常或异常消息。

同样

打印(better_calc(5, *, 5))

这会返回 ''SyntaxError: invalid syntax'',不会触发异常或异常消息。

我意识到,如果我在运算符上包含引号,代码会起作用,但是,我的目标是触发异常。

def better_calc(num1, op, num2):
    try:
        if op == "+":
            result = num1+num2
        elif op == "-":
            result = num1-num2
        elif op == "*":
            result = num1*num2
        elif op == "/":
            num1/num2
    except NameError:
        print(f"Error: Name error. Please check your input")
    except UnboundLocalError:
        print(f"Error: Value error. Please check your input")
    except SyntaxError:
        print(f"Error: Syntax Error. Please check your input")

    print(num1, op, num2, "=")
    return result

print(better_calc(5, 5, 5))

【问题讨论】:

  • 因为错误发生在您的函数外部;它永远不会被调用,因此不可能捕获它。您无法捕获语法错误(在 exec/eval 之外),因为如果您的代码在语法上无效它无法运行
  • 您能澄清一下您要做什么吗?参数在传递给函数之前被评估——在函数内部捕获错误不包括格式错误的参数语法或名称。此外,运算符不是一流的——例如,您不能将 + 运算符传递给函数。为此使用operator.add - 尽管您的函数被编写为期望字符串 +,而不是相应的操作。
  • SyntaxErrors 不能被代码捕获:它们是在编译时引发的,此时 Python 在执行之前将整个源代码解析为字节码,而不是在实际运行时。

标签: python python-3.x


【解决方案1】:

只是为了巩固 cmets 中已经给出的答案,try/except 块只能处理在 try: 和第一个 except 块之间引发的错误。

try:
    # raised exceptions in this block can be caught
    foo = "bar"
except FooError:
    # catches a raised FooError but any exceptions raised here are
    # outside of the try block and will not be handled. Another try/except
    # block could be added here to catch these exceptions
    pass
except Exception as e:
    # a trick to log exceptions but then let the exception run
    print(e)
    raise

对函数 print(better_calc(5, g, 5)) 的调用在函数的 try 块之外,不会被捕获。

print(better_calc(5, *, 5)) 这样的语法错误使程序无法运行,这绝对是在函数的try 块之外。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 2022-11-29
    • 1970-01-01
    • 2015-06-21
    • 2011-05-27
    • 1970-01-01
    相关资源
    最近更新 更多