2014-10-05 40 views
0

我得到這個錯誤:TypeError:我的代碼不支持的操作數類型?

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

你爲什麼試圖捕捉一個'ZeroDivisionError'? – 2014-10-05 20:22:09

回答

4

的OP規定:除非你趕上正確的錯誤

I'm learning about exception handling.I know that there'll be an error for the 5 + ham and that i shouldnt see the "wont see this", but why am I getting this error?

的代碼將產生一個錯誤。在這種情況下,正確的錯誤是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") 
+1

爲什麼要使用'ZeroDivisionError'? – 2014-10-05 20:22:42

+2

@PadraicCunningham他正在學習異常處理 – AHuman 2014-10-05 20:23:18

+0

@PadraicCunningham好點。我剛剛從OP的問題中添加了一段引文,以澄清OP的意圖是嘗試異常處理。 – John1024 2014-10-05 20:25:01

相關問題