首页 > 解决方案 > 如何在 Python 中创建自定义错误消息

问题描述

我将如何在 python 中创建自定义错误消息而不将每个语句包装在一个try-except子句中?例如(假设 python3.6),假设我在 python 提示符中输入以下代码:

the_variable=5
print(the_varible)

这将返回:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'the_varible' is not defined

假设我想返回一个自定义异常:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'the_varible' is not defined. Did you mean 'the_variable'?

当然,这是一个非常人为的示例,我可以轻松地将这个特定示例包装在一个try: except子句中(例如,这里这里和许多其他示例),但我更一般想要的是自定义程序中所有语句的任何错误消息

例如,如果我创建一个名为 的文件my_script.py,其中包含:

the_variable=5
print(the_varible)

我用python my_script.py. 我想收到与上面相同的自定义错误消息。

标签: pythonerror-handlingcustomization

解决方案


您可以捕获main()函数中的所有错误,这通常是应用程序的启动函数。

def main():
    try:
        // all the rest of your code goes here
    except NameError as err:
        // your custom error handling goes here
    // other custom error handlers can go here

推荐阅读