我将如何在 python 中创建自定义错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20844347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:22:11  来源:igfitidea点击:

How would i make a custom error message in python

pythonpython-3.x

提问by user2196227

In a python program I am making, I want it to only take integers, and if it gets a string say "There has been an error in the system." instead of murmering sensless information the user will not understand

在我正在制作的 python 程序中,我希望它只接受整数,如果它得到一个字符串,请说“系统出现错误”。而不是抱怨用户不会理解的毫无意义的信息

回答by K DawG

Use a try-exceptblock to capture the error and use the raisestatement to say the error message of your choice:

使用try-except块捕获错误并使用raise语句说出您选择的错误消息:

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

回答by rlms

You need to use a tryexceptblock to catch the error - see the documentation. Then you could just printa message, and, if necessary, exit the program:

您需要使用tryexcept块来捕获错误 - 请参阅文档。然后,您可以只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)

回答by Universal Link

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

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

回答by user1251007

If you do not want to add another indentation level by using a try-exceptblock, you can change the handling of all errors by adding the following to the beginning of your code:

如果您不想使用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

In case of an error, only your specified error message is printed out. In addition, this prevents the stack trace from being displayed.

如果出现错误,只会打印出您指定的错误消息。此外,这可以防止显示堆栈跟踪

回答by Mr Python

If you want to make an error, you use raise. Here is an example:

如果你想出错,你可以使用 raise。下面是一个例子:

raise SyntaxError('MUHAHA THIS IS A ERROR')

this is the simplest way, I have no idea what tryand exceptdoes

这是最简单的方法,我不知道什么tryexcept