简体   繁体   English

为什么出现 NameError 时异常语句不执行?

[英]Why does the exception statement not executes when NameError occurs?

After defining a function and try/except/else statements in the following way:通过以下方式定义 function 和 try/except/else 语句后:

def divide(a, b):
    try:
        a / b
    except:
        return False, 'Error occurred'
    else:
        return True, 'Division successful'

The exception is not raised when the argument given to the function is a name of an undefined variable.当提供给 function 的参数是未定义变量的名称时,不会引发异常。 For instance:例如:

divide(2, J)

instead of executing block of code under except statement, following error is displayed:而不是在 except 语句下执行代码块,而是显示以下错误:

NameError: name 'J' is not defined

I have tried rewriting the except statement ( except NameError: ), but to no avail.我曾尝试重写 except 语句( except NameError: ),但无济于事。

I would be grateful if someone could explain why the except statement is not executed in this case, and how can the execution of it be ensured in case of NameError?如果有人能解释为什么在这种情况下不执行 except 语句,我将不胜感激,如果出现 NameError,如何确保它的执行?

J is a variable in your case, which is not defined. J在您的情况下是一个变量,未定义。 Even before the function runs, J is being called but doesn't exists, hence your error: name 'J' is not defined.甚至在 function 运行之前, J被调用但不存在,因此您的错误:名称“J”未定义。 I assume you want to test your function with divide(2, "J") which passes the parameter as a string.我假设您想使用将参数作为字符串传递的divide(2, "J")来测试您的 function。 That should raise the except as desired.这应该会根据需要提高 except 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM