问题
This is a follow up to an older question.
Given a ISBN number, e.g. 3-528-03851-5
which exception type should I raise if the passed in string doesn't match the format X-XXX-XXXXX-X?
回答1:
Raise a ValueError
.
It's pretty much the standard way of saying "you've given me a value that doesn't make sense". For example:
>>> int("a") Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'a' >>> import shlex; shlex.split("'") Traceback (most recent call last): ... ValueError: No closing quotation
Contrast this with a TypeError
, which is raised when a type is incorrect:
>>> d = {} >>> d[{}] Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'dict'
回答2:
I think I'd make an exception class to raise in this instance since its a very specific type of exception. You can extend the ValueError class pretty easily:
class ISBNFormatException(ValueError):
"""Raised when an invalid ISBN format is found"""
pass
回答3:
The ValueError might be the most appropriate choice. According to its docs, it's when a value has the correct type but an inappropriate value.
http://docs.python.org/library/exceptions.html#exceptions.ValueError
来源:https://stackoverflow.com/questions/4047752/which-exception-to-raise-if-a-given-string-does-not-match-some-format