我正在练习异常处理,当我尝试执行以下代码时,如果我输入文本而不是数字,python 不会处理 TypeError 异常。以下是代码:
num1=input("Enter the first number : ")
num2=input("Enter the second number : ")
try:
num1=int(num1)
num2=int(num2)
except TypeError:
print("Sorry, that wasn't a number, please try again")
else:
print(add)
这是因为您没有跟踪正确的错误:
>>> int("not a number")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'not a number'
ValueError 就是你正在寻找的。