对于 Python 中的错误/非法参数组合,我应该引发哪个异常? [英] Which exception should I raise on bad/illegal argument combinations in Python?
问题描述
我想知道在 Python 中指示无效参数组合的最佳实践.我遇到过几种情况,您有这样的功能:
I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so:
def import_to_orm(name, save=False, recurse=False):
"""
:param name: Name of some external entity to import.
:param save: Save the ORM object before returning.
:param recurse: Attempt to import associated objects as well. Because you
need the original object to have a key to relate to, save must be
`True` for recurse to be `True`.
:raise BadValueError: If `recurse and not save`.
:return: The ORM object.
"""
pass
唯一的烦恼是每个包都有自己的,通常略有不同的BadValueError
.我知道在 Java 中存在 java.lang.IllegalArgumentException
-- 是否很好理解每个人都会在 Python 中创建自己的 BadValueError
或者是否有另一种首选方法?
The only annoyance with this is that every package has its own, usually slightly differing BadValueError
. I know that in Java there exists java.lang.IllegalArgumentException
-- is it well understood that everybody will be creating their own BadValueError
s in Python or is there another, preferred method?
推荐答案
我只想提出 ValueError,除非您需要更具体的异常..
I would just raise ValueError, unless you need a more specific exception..
def import_to_orm(name, save=False, recurse=False):
if recurse and not save:
raise ValueError("save must be True if recurse is True")
执行 class BadValueError(ValueError):pass
真的没有意义 - 您的自定义类在使用上与 ValueError,那么为什么不使用它呢?
There's really no point in doing class BadValueError(ValueError):pass
- your custom class is identical in use to ValueError, so why not use that?
这篇关于对于 Python 中的错误/非法参数组合,我应该引发哪个异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!