3

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?

Community
  • 1
  • 1
helpermethod
  • 59,493
  • 71
  • 188
  • 276

3 Answers3

6

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'
David Wolever
  • 148,955
  • 89
  • 346
  • 502
3

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
dcolish
  • 22,727
  • 1
  • 24
  • 25
2

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

voodoogiant
  • 2,118
  • 6
  • 29
  • 49