[英]Which exception to raise if a given string does not match some format?
This is a follow up to an older question . 这是对旧问题的跟进。
Given a ISBN number, eg 3-528-03851-5
which exception type should I raise if the passed in string doesn't match the format X-XXX-XXXXX-X? 给定一个ISBN号,例如
3-528-03851-5
如果传入的字符串与格式X-XXX-XXXXX-X不匹配,我应该提出哪种例外类型?
Raise a ValueError
. 提出
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: 将此与
TypeError
对比, TypeError
在类型不正确时引发:
>>> d = {} >>> d[{}] Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'dict'
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:
您可以非常轻松地扩展ValueError类:
class ISBNFormatException(ValueError):
"""Raised when an invalid ISBN format is found"""
pass
The ValueError might be the most appropriate choice. ValueError可能是最合适的选择。 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 http://docs.python.org/library/exceptions.html#exceptions.ValueError
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.