Python 例外处理程序未按预期工作

Python exeception handler not working as expected

提问人:rkg125 提问时间:6/17/2023 更新时间:6/17/2023 访问量:30

问:

我正在编写一个交互式计算器,其中包含数十个我自己的函数。有些函数有字符串参数,有些函数有数字参数。

对于字符串情况,如果我不小心输入了一个字符串,没有引号,我希望脚本打印出我自己的错误消息,说“参数必须是带引号的字符串”,然后继续。

这是我正在编写的函数的形状

def sample_function(x):
        try:
              if type(x) is str:
                   # do some calculation
                   print(x)
              else:
                   pass
        except NameError:
                   print(“ argument must be a quoted string”)

只要我输入sample_function('a'),一切都很好,但是如果我输入samole_function(a), 该脚本不是打印我的消息并继续,而是以系统错误消息终止

    NameError: name 'a' is not defined

一定有一种方法可以让执行处理程序做我想做的事。

python 函数 try-except

评论

4赞 B Remmelzwaal 6/17/2023
这是因为 NameError 甚至在您调用函数之前就已引发,因此您甚至永远不会到达 try-except 块。
0赞 chepner 6/17/2023
通常,您不应该抓住 ;您应该修复生成它的代码。NameError

答:

1赞 picobit 6/17/2023 #1

您收到该错误,因为未定义。令人震惊,我知道。a

您正在引用一个名为 的对象,但尚未创建它。这与尝试打印不存在的变量是一回事。a

>>> print(mystring)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'mystring' is not defined

不过,这有效。

>>> mystring="Hello world!"
>>> print(mystring)
Hello world!

看?

def sample_function(x):
    # Lose the try/except here
    if type(x) is str:
        # do some calculation
        print(x)
    else:
        print("That wasn't a string!")

                         
# This doesn't work
try:
    sample_function(a)
except NameError:
    print("That didn't work")

# This works
a = "a string"
sample_function(a)

# And this works too
a = 123
sample_function(a)

# Output:
#   That didn't work
#   a string
#   That wasn't a string!