如何在python中生成自定义错误消息

如何在python中生成自定义错误消息,python,python-3.x,Python,Python 3.x,在我正在编写的python程序中,我希望它只接受整数,如果它得到一个字符串,就说“系统中有一个错误。”用户不会理解无意义的信息,而是使用try except块捕获错误,并使用raise语句说出您选择的错误消息: try: a = int(input()) except: raise Exception('There has been an error in the system') 您需要使用try块来捕获错误-请参阅。然后,您可以打印一条消息,如有必要,退出程序: try:

在我正在编写的python程序中,我希望它只接受整数,如果它得到一个字符串,就说“系统中有一个错误。”用户不会理解无意义的信息,而是使用
try except
块捕获错误,并使用
raise
语句说出您选择的错误消息:

try:
    a = int(input())
except:
    raise Exception('There has been an error in the system')

您需要使用
try
块来捕获错误-请参阅。然后,您可以打印一条消息,如有必要,退出程序:

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)
你可以试试这个

import ctypes
ctypes.windll.user32.MessageBoxW(None, u"CUSTOM MESSAGE", u"TITLE BAR", 0)

如果不想使用
try except
块添加另一个缩进级别,可以通过在代码开头添加以下内容来更改对所有错误的处理:

import sys
def my_except_hook(exctype, value, traceback):
        print('There has been an error in the system')
sys.excepthook = my_except_hook

如果出现错误,则只打印指定的错误消息。此外,这将阻止堆栈跟踪显示

如果要出错,请使用raise。以下是一个例子:

raisesyntaxerror('MUHAHA这是个错误')
使用
尝试
除外
升高
由于
ValueError
继承自
Exception
类,因此创建
ValueError
对象时的第一个参数是它打印的消息:

试试看:
int(“string”)#引发错误的代码
除值错误外:
raise VALUERROR(“此处为您的自定义消息”)
这张照片是:

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.
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError: Your custom message here.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: Your custom message here.
这张照片是:

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.
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError: Your custom message here.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: Your custom message here.
这张照片

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.
这张照片是:

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.
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError: Your custom message here.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: Your custom message here.
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AssertionError:这里是您的自定义消息。
尽管使用
assert
看起来很干净,但错误不会携带太多信息,因为它是一个通用的
AssertionError
。引发一个
ValueError
一眼就能告诉您有关错误原因的更多信息。

使用
raiseexception(“系统中有错误”)
可能对大多数情况很有用,但您可能还需要为特定系统创建有意义的错误

例如


类ExpiredTaxIdException(异常):
定义初始化(自):
例外情况。uuu init_uuuuu(self,'Tax ID expired')
然后您可以在代码中调用它,示例:


从您的_execeptions_文件导入ExpiredTaxIdException
类ClientsController:
def是_profile_有效(客户端):
如果client.tax\u id.is\u valid==False:
引发过期的TaxidException()
返回真值
#你在你的API上调用它,在你代码的另一个地方不能接受无效的税号
尝试:
ClientsController()。验证客户端(客户端)
除过期的AxidException外,e:
返回{'error':str(e)}
>>>{“错误”:“税务ID已过期”}

您的解决方案提供了一条有意义的错误消息,但仍将显示堆栈跟踪。堆栈跟踪可能会吓跑用户,因为它与用户基本无关。不要使用裸跟踪,因为这会隐藏错误。使用适当的,除了…可能重复的不是“系统中有错误”。这是用户无法理解的无意义信息的一个很好的例子?:-)请接受答复