TypeError:我的代码不支持的操作数类型?

时间:2014-10-05 20:15:12

标签: python python-3.4

我收到此错误:

Traceback (most recent call last):   
File "exceptionhandling.py", line 2, in <module>
     x = 5 + "ham" TypeError: unsupported operand type(s) for +: 'int' and 'str'

我的代码:

try:
    x = 5 + "ham"

except ZeroDivisionError:
    print("won't see this")
finally:
    print("The final word")

我正在学习异常处理。我知道5 + "ham"会出现错误,我不应该看到"won't see this",但为什么会收到此错误?

1 个答案:

答案 0 :(得分:4)

OP表示:

  

我正在学习异常处理。我知道会有错误   5 +火腿,我不应该看到“不会看到这个”,但为什么   我收到此错误吗?

除非您发现正确的错误,否则代码将引发错误。在这种情况下,正确的错误是TypeError

try:
    x = 5 + "ham"

except ZeroDivisionError:
    print("won't see this")
except TypeError:
    print("Hey, these are the wrong types!")
finally:
    print("The final word")

此代码的输出为:

Hey, these are the wrong types!
The final word

如果您想捕获每个错误,请执行以下操作:

try:
    x = 5 + "ham"

except:
    print("Something went wrong.")
finally:
    print("The final word")