在我正在制作的python程序中,我希望它只采用整数,如果它得到一个字符串,则说"系统中存在错误".用户不会理解,而不是篡改敏感的信息
K D*_*awG 10
使用try-except块来捕获错误并使用该raise语句来说出您选择的错误消息:
try:
a = int(input())
except:
raise Exception('There has been an error in the system')
Run Code Online (Sandbox Code Playgroud)
您需要使用try except块来捕获错误 - 请参阅文档。然后,您可以只print发送一条消息,并在必要时退出程序:
try:
value = int(input("Enter an integer: "))
except ValueError:
print("There has been an error in the system.")
input() # To let the user see the error message
# if you want to then exit the program
import sys
sys.exit(1)
Run Code Online (Sandbox Code Playgroud)
如果你想犯错误,你可以使用 raise。这是一个例子:
raise SyntaxError('MUHAHA THIS IS A ERROR')
Run Code Online (Sandbox Code Playgroud)
try,except和raise由于ValueError继承自Exception类,因此创建ValueError对象时的第一个参数是它打印的消息:
try:
int("string") #the code that raises the error
except ValueError:
raise ValueError("Your custom message here.")
Run Code Online (Sandbox Code Playgroud)
这打印:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'string'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: Your custom message here.
Run Code Online (Sandbox Code Playgroud)
如果您不想打印之前的错误链,请from None输入以下raise语句:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'string'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: Your custom message here.
Run Code Online (Sandbox Code Playgroud)
这打印:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: Your custom message here.
Run Code Online (Sandbox Code Playgroud)
我建议您离开该链,因为它提供了更多信息,例如引发错误的输入内容。如果要在自定义消息中包含来自原始错误的信息,请使用错误的属性:
try:
int("string") #the code that raises the error
except ValueError:
raise ValueError("Your custom message here.") from None
Run Code Online (Sandbox Code Playgroud)
这打印
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: Custom message with traceback and message
File "<stdin>", line 2, in <module>
invalid literal for int() with base 10: 'string'
End of error message.
Run Code Online (Sandbox Code Playgroud)
虽然这允许自定义错误的打印,但代码有点不符合 Python 风格。
assert因为在您说要阻止所有字符串的问题中,您可以使用assertand isinstance():
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: Your custom message here.
Run Code Online (Sandbox Code Playgroud)
这打印:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Your custom message here.
Run Code Online (Sandbox Code Playgroud)
虽然 usingassert看起来很干净,但错误不会携带那么多信息,因为它是一个通用的AssertionError. 提高ValueErrora 一目了然地告诉了有关导致错误的原因的更多信息。
| 归档时间: |
|
| 查看次数: |
26699 次 |
| 最近记录: |