异常处理Python3

时间:2016-06-09 08:21:14

标签: python-3.x exception-handling typeerror

我正在练习异常处理,当我尝试执行以下代码时,如果输入文本而不是数字,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)

1 个答案:

答案 0 :(得分:1)

这是因为您没有跟踪正确的错误:

>>> 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。