如何实现带有自定义消息的自定义 Python 异常?
pythonserver side programmingprogramming更新于 2025/6/25 16:12:17
对于上面给出的代码,解决方案如下
示例
class CustomValueError(ValueError):
def __init__(self, arg):
self.arg = arg
try:
a = int(input("输入一个数字:"))
if not 1 < a < 10:
raise CustomValueError("值必须在 1 和 10 之间。")
except CustomValueError as e:
print("CustomValueError Exception!", e.arg)
输出
输入一个数字:45 CustomValueError Exception!值必须在 1 到 10 之间。 Process finished with exit code 0
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

