What are good names for custom exceptions?

This question covers a wide range of programming languages; however, I specifically work with Python in this case.

I would like to create some custom exceptions, but I'm not sure how fine 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 end time is before the start, but could I name 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 caught)

I am sure there are other ways to look at this, and therefore more options to indicate an exception. Are there any standards or guidelines that describe this?

+4
source share
2 answers

I think inline ValueError might be appropriate in this case. From Python docs:

ValueError exception

Raised when a built-in work or function receives an argument that is of the correct type, but of an inappropriate value, and the situation does not describe a more precise exception, such as IndexError.

+6
source

I try to make the most of the appropriate built-in exceptions as much as possible. In languages ​​like Java and C #, the exception list is so consistent that you rarely find one that you need to define yourself. I'm not very familiar with the Python exception list, but IIRC has at least a few pretty good ones.

+1
source

All Articles