Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: Should I use ValueError or create my own subclass to handle invalid strings? [duplicate]

Possible Duplicate:
Which exception should I raise on bad/illegal argument combinations in Python?

I've looked through python's built in exceptions and the only thing that seems close is ValueError.

from python documentation:

exception ValueError: Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

Should I create a subclass of ValueError, like InvalidFormatException?

(My particular case is if a roman numeral string is improperly formatted, but there are many other applicable cases.)

EDIT: it seems like ValueError is the right choice, now the issue is whether to use ValueError directly or to subclass it.

like image 414
Gordon Gustafson Avatar asked Jan 02 '10 16:01

Gordon Gustafson


People also ask

What is the difference between ValueError and TypeError in Python?

A TypeError occurs when an operation or function is applied to an object of inappropriate type. A ValueError occurs when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

How does Python handle ValueError?

Handling ValueError Exception Here is a simple example to handle ValueError exception using try-except block. import math x = int(input('Please enter a positive number:\n')) try: print(f'Square Root of {x} is {math. sqrt(x)}') except ValueError as ve: print(f'You entered {x}, which is not a positive number.

What is a ValueError in Python?

The ValueError exception in Python is raised when the method receives the argument of the correct data type but an inappropriate value. The associated value is a string giving details about the data type mismatch.


1 Answers

ValueError is a good match for the case you have. Just go with that and remember that you can specify a useful message as an argument, letting you distinguish this from other types of ValueError.

I would not make the code more complicated by defining a subclass, however, unless I had a good reason to want to catch just that particular error but avoid catching any other ValueErrors. Many applications have dozens of "special" error conditions, but if they also defined per-case subclasses the code would quickly get unmaintainable and anyone trying to use the routines would be constantly surprised by the unexpected new exceptions.

like image 156
Peter Hansen Avatar answered Oct 19 '22 19:10

Peter Hansen