views:

38

answers:

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?

+5  A: 

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
+2  A: 

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

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