开发者

How does one indicate invalid arguments in Python? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

python: Should I use ValueError or create my own subclass to handle invalid strings?

Reading Built-in Exceptions I read:

All user-defined exceptions should also be derived from this class" with regards to Exception.

I also see a ValueError which says:

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

If I want to raise an exception for invalid arguments (the equivalent of Ruby's ArgumentError), what should I do? Should I raise ValueError directly, or preferably subclass ValueError with my own intention revealing name?

In my case, I accept a key argume开发者_如何学Pythonnt, but I want to restrict the set of characters in the key, such that only /\A[\w.]+\Z/ (Perl/Ruby regular expression) is accepted.


I think the general idea is this: ValueError should almost always denote some sort of client error (where 'client' means the programmer using your interface). There are two high-level types of exceptions in Python:

  • uncommon cases for otherwise normally functioning code; the client is not to blame

  • usage errors where some interface is used incorrectly, or the through a series of interface calls, the system has reached an inconsistent state; time to blame the client

In my opinion, for the first case, it makes sense to create exception class hierarchies to allow client code fine-grained control over what to do in uncommon cases.

In the second case, and ValueError is an example of this, you are telling the client that they did something wrong. Fine-grained exception hierarchies are not as important here, because client code probably should be fixed to do the right thing (e.g., pass the right parameter types in the first place).

TL;DR: Just use ValueError, but include a helpful message (e.g., raise ValueError("I'm afraid I can't let you do that, Dave. -HAL 9000"). Don't subclass unless you genuinely expect someone to want to catch SubClassError but not other ValueErrors.

With that said, as you've mentioned, the Python built-in library does subclass ValueError in some cases (e.g. UnicodeError).


ValueError seems to cover your situation quite well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜