2017-07-26 33 views
-1
try: 
    grossCheck = int(input("How much? (figures only pls.)\n")) 
except ValueError: 
    grossCheck = int(input("How much? (FIGURES ONLY PLS.)\n")) 

tenPees = grossCheck * 0.1 
realPees = grossCheck - tenPees 

print("you've got " + str(realPees)) 

我得到:如何在處理同一個異常時保護我的程序免受其他異常的影響?

ValueError: invalid literal for int() with base 10: 'w' 

During handling of the above exception, another exception occurred: 

的事情是我之前剛處理相同的異常。 我試圖處理它,以防萬一用戶在不破壞程序的情況下多次輸入錯誤的值。

+8

你需要顯示你的代碼,和完整的追溯。鑑於數據不足。 –

回答

0

你需要以某種方式處理異常。一種方法是不斷地問:

try: 
    grossCheck = int(input("How much? (figures only pls.)\n")) 
except ValueError: 
    while True: 
     try: 
      grossCheck = int(input("How much? (FIGURES ONLY PLS.)\n")) 
      break 
     except ValueError: 
      pass 
+0

爲什麼你在try和catch塊中重複代碼,檢查我的答案,看看更好的處理錯誤的方式 –

+0

我重複自從OP重複並且我複製了他的功能,但修復了他所問的錯誤。還要注意他在'input'中有不同的字符串。 –

+0

沒關係,你可以根據需要更改字符串,但while循環不應該在block內部,如果你有5個錯誤,而不是ValueError,那麼除了你需要的5個錯誤之外,除了每個錯誤 –

0
while 1: 
    try: 
     grossCheck = int(input("How much? (figures only pls.)\n")) 
     tenPees = grossCheck * 0.1 
     realPees = grossCheck - tenPees 

     print("you've got " + str(realPees)) 
    except ValueError: 
     print('You must enter number') 

這是錯誤處理的正確途徑之一。 你得到的錯誤,是因爲你已經把輸入放在除了塊以外,你不應該這樣做,除非你應該打印錯誤,如果你想要或者只是重複嘗試塊

相關問題