當用戶輸入零時,輸出下面的代碼“不要除以零,這是被禁止的”很好,但是如果輸入一個句子或字符,它會回傳一個 ValueError。錯誤如下:
Traceback (most recent call last):
File "exceptions.py", line 5, in <module>
num2 = int(input())
ValueError: invalid literal for int() with base 10: 'Hello World'
代碼來自 PicoCTF 的教程部分,可以在下面找到:
我試過改變:
except TypeError:
print("Your input value must be an integer.")
到
except Value Error:
print("Your input value must be an integer.")
num1 = 8
print("Input the number that will divide:")
num2 = int(input())
try:
result = num1 / num2
print(result)
except ZeroDivisionError:
print("Do not divide by zero, that is forbidden.")
except TypeError:
print("Your input value must be an integer.")
print("The program keeps executing to do other stuff...")
但是它仍然沒有輸出我輸入的例外。我錯過了什么嗎?供參考,我使用的是 picoCTF 的內部 web shell 提前謝謝大家的支持。
uj5u.com熱心網友回復:
ValueError發生在通話int(...)中。如果要處理它,則需要try:在該代碼周圍添加一個塊。例如:
num1 = 8
print("Input the number that will divide:")
num2_str = input()
try:
num2 = int(num2_str)
except ValueError:
print(f"this isn't an integer: {num_str}")
num2 = 0 # or whatever you want the default to be
try:
result = num1 / num2
print(result)
except ZeroDivisionError:
print("Do not divide by zero, that is forbidden.")
except TypeError:
print("Your input value must be an integer.")
print("The program keeps executing to do other stuff...")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458718.html
上一篇:傳遞多個引數...使用增強的for回圈,導致ArrayIndexOutOfBoundsExceptionJAVA
下一篇:處理變數但數量有限的引數
