代码之家  ›  专栏  ›  技术社区  ›  helpermethod

如果给定的字符串与某些格式不匹配,则引发哪个异常?

  •  3
  • helpermethod  · 技术社区  · 15 年前

    older question .

    给定ISBN号,例如。 3-528-03851-5

    3 回复  |  直到 9 年前
        1
  •  6
  •   David Wolever    15 年前

    提高 ValueError .

    >>> 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
    
    

    把这个和 TypeError ,当类型不正确时引发:

    >>> d = {}
    >>> d[{}]
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: unhashable type: 'dict'
    
        2
  •  3
  •   dcolish    15 年前

    class ISBNFormatException(ValueError):
        """Raised when an invalid ISBN format is found"""
        pass
    
        3
  •  2
  •   voodoogiant    15 年前

    ValueError可能是最合适的选择。根据它的文档,当一个值具有正确的类型但不适当的值时。

    http://docs.python.org/library/exceptions.html#exceptions.ValueError