问题描述
我已经看过python的内置异常,唯一似乎很接近的是ValueError。
I've looked through python's built in exceptions and the only thing that seems close is ValueError.
从python文档:
我应该创建一个ValueError的子类,像InvalidFormatException?
Should I create a subclass of ValueError, like InvalidFormatException?
(我的具体情况是如果一个罗马数字字符串格式不正确,但还有很多其他应用电缆案例。)
(My particular case is if a roman numeral string is improperly formatted, but there are many other applicable cases.)
编辑:看起来ValueError是正确的选择,现在的问题是是否直接使用ValueError或将其子类化。
推荐答案
ValueError
是一个很好的匹配。只要一起去记住,你可以指定一个有用的消息作为参数,让你区别于其他类型的ValueError。
ValueError
is a good match for the case you have. Just go with that and remember that you can specify a useful message as an argument, letting you distinguish this from other types of ValueError.
我不会使代码更复杂但是,通过定义一个子类,除非我有一个很好的理由想要捕捉那个特定的错误,而且避免捕获任何其他ValueErrors。许多应用程序有几十个特殊错误条件,但是如果它们也定义了每个子类的代码,那么代码将很快变得不可维护,任何试图使用这些例程的人都会不断地惊讶于新的异常。
I would not make the code more complicated by defining a subclass, however, unless I had a good reason to want to catch just that particular error but avoid catching any other ValueErrors. Many applications have dozens of "special" error conditions, but if they also defined per-case subclasses the code would quickly get unmaintainable and anyone trying to use the routines would be constantly surprised by the unexpected new exceptions.
这篇关于python:我应该使用ValueError还是创建我自己的子类来处理无效的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!