Take the 2-minute tour ×

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?

share|improve this question
add comment

3 Answers

up vote 5 down vote accepted

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'
share|improve this answer
add comment

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"""
share|improve this answer
+1 for the most Pythonic answer –  smci Jun 24 '11 at 21:06
add comment

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.


share|improve this answer
add comment

Your Answer


