Python 3.4中的自定义异常代码和消息
我希望有一个自定义的错误代码/消息数据库,并在引发异常时使用它(在Python 3.4中)。因此,我做了以下工作:Python 3.4中的自定义异常代码和消息,python,Python,我希望有一个自定义的错误代码/消息数据库,并在引发异常时使用它(在Python 3.4中)。因此,我做了以下工作: class RecipeError(Exception): # Custom error codes ERRBADFLAVORMIX = 1 ERRNOINGREDIENTS = ERRBADFLAVORMIX + 1 # Custom messages ERRMSG = {ERRBADFLAVORMIX: "Bad flavor mix
class RecipeError(Exception):
# Custom error codes
ERRBADFLAVORMIX = 1
ERRNOINGREDIENTS = ERRBADFLAVORMIX + 1
# Custom messages
ERRMSG = {ERRBADFLAVORMIX: "Bad flavor mix",
ERRNOINGREDIENTS: "No ingredients to mix"}
raise RecipeError(RecipeError.ERRMSG[RecipeError.ERRBADFLAVORMIX])
这正如预期的那样工作,但是
raise
语句非常可怕。当然,我可以用一种更紧凑的方式存储这些值,但我真正想知道的是:我可以做一些类似于提高RecipeError(code)
的事情,然后把获取消息的工作留给RecipeError吗?当然可以。异常类只是普通类,因此您可以定义自己的\uuuu init\uuu
调用super
:
class RecipeError(BaseException):
# existing stuff
def __init__(self, code):
super().__init__(self, RecipeError.ERRMSG[code])
您可能还希望保存代码:
class RecipeError(BaseException):
# existing stuff
def __init__(self, code):
msg = RecipeError.ERRMSG[code]
super().__init__(self, msg)
self.code, self.msg = code, msg
看看标准库中存储的异常信息(在3.4中相当不错,尽管还有更多的变化…),看看哪些类型的东西可能有用
一些旁注:
首先,最好使用子类而不是错误代码。例如,如果有人想要编写捕获
ERRBADFLAVORMIX
而不是errnoingElements
的代码,他们必须这样做:
try:
follow_recipe()
except RecipeError as e:
if e != RecipeError.ERRBADFLAVORMIX:
raise
print('Bad flavor, bad!')
或者,如果您使用了子类:
try:
follow_recipe():
except BadFlavorRecipeError as e:
print('Bad flavor, bad!')
这正是为什么Python不再有一个带有必须打开的errno
值的单片OSError
,而是有单独的子类,如FileNotFoundError
如果您确实想使用错误代码,您可能需要考虑使用AN,或者可能会更容易将自定义字符串附加到每一个。
您几乎不想从
BaseException
继承,除非您特别尝试确保您的异常不会被捕获。谢谢您提供的附加信息。我很确定我读到所有用户定义的异常都应该从BaseException
中派生出来,所以我错了。