Category Hierarchy

目前正在学习try和except,并尝试通过除以数字来捕获错误

这是我的代码:

def divide(a, b): 
    try:
        return a/b
    except ZeroDivisionError: 
        return "dividing by zero not possible "
    except TypeError:
        return "a and b must both be integers"
    except NameError:
        return "a and b must both be integers"


print(divide(2,a))

但由于某些原因,当我将第二个值设为‘a’并返回此错误时,它无法捕获TypeError和NameError:

Traceback (most recent call last):
  File "d:/Python/Learning-Python/Section 18/Section_18_errors.py", line 24, in <module>
    print(divide(2,a))
NameError: name 'a' is not defined

我的try and expect捕捉到了NameError,对吗?它不应该返回"a和b都必须是整数“吗?

转载请注明出处:http://www.yojatech.com/article/20230526/1859851.html