python - 如何在 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
. 我想收到与上面相同的自定义错误消息。
解决方案
您可以捕获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
推荐阅读
- javascript - Selenium - 使用 java 脚本输入文本
- python - CVXOPT 在稳健最小二乘期间产生 nan
- go - 基本类型的解引用接口
- c++ - Endianness when order of bits (rather than bytes) is crucial
- java - Java 完全替代 getScaledInstance(width, height, Image.SCALE_SMOOTH)
- html - 如何获取一行中每个单元格的值并将其分配给该行中的文本框
- java - 如何使用 java 代理和 ASM 动态记录任何调用的 java 方法的所有参数?
- scala - 使用 SparkSQL 读取多个 parquet 文件时将子文件夹作为列获取
- javascript - 如何在 Gatsby(React) 中实现 document.getElementById
- json - 我们如何将 Mule 4 dataweave 2.0 代码转换为 Mule 3 dataweave 1.0?