views:

134

answers:

2

This question covers a broad range of programming languages; however, I am specifically working with Python in this case.

I would like to create some user defined exceptions, but I'm not sure how fine-grained they should be. For example, if I have the following class:

class Race(object):
    def __init__(self, start_time, end_time):
        if end_time < start_time:
            raise WhatToNameThisError
        self._start_time = start_time
        self._finish_time = end_time

I would like an exception to be raised if the finish time occurs before the start time, but I could I call it?

  • RaceError (all exceptions related to the Race class can use this, and the message can distinguish between them)
  • RaceFinishTimeBeforeStartTime (more specific, but means I know exactly what I'm catching)

I'm sure there are other ways of looking at this, and thus more options for naming an exception. Are there any standards or guidelines which outline this?

+4  A: 

I think the built-in ValueError may be appropriate in this case. From the Python docs:

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.

dcrosta
'User code can raise built-in exceptions. This can be used ... to report an error condition “just like” the situation in which the interpreter raises the same exception' from http://docs.python.org/library/exceptions.html
dcrosta
This is good enough for most cases.
rioch
A: 

I try to use appropriate built-in exceptions as much as possible. In languages like Java and C# the exception list is so robust that you'll rarely find one you need to define yourself. I'm not super-familiar with Python's exception list, but IIRC there are at least a few pretty general good ones.

phoebus