为什么 TextError 异常在此代码中无法正常运行?
Why do TextError exceptions not function properly in this code?
当用户输入零时,输出“不要被零除,这是禁止的”下面的代码很好,但是如果输入了一个句子或字符,它 returns 一个 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 的内部网络 shell
预先感谢大家的支持。
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...")
当用户输入零时,输出“不要被零除,这是禁止的”下面的代码很好,但是如果输入了一个句子或字符,它 returns 一个 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 的内部网络 shell 预先感谢大家的支持。
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...")