preconditions and exceptions

exception, language-agnostic, preconditions

Solution

Yes and no.

Yes - Violating a precondition is certainly an appropriate time to throw an exception. Throwing a more specific exception will make catching that specific exception simpler.

No - Declaring a new exception class for every precondition in your program/api seems way overkill. This could result in hundreds or thousands of exceptions eventually. This seems a waste both mentally and computationally.

I would recommend throwing exceptions for precondition violations. I would not, however, recommend defining a new exception for each precondition. Instead, I would recommend creating broader classes of exceptions that cover a specific type of precondition violation, rather than a specific precondition violation. (I would also recommend using existing exceptions where they fit well.)

Problem

Suppose you have a method with some pre and post-conditions. Is it ok to create an exception class for each pre-condition that is not accomplished? For example: Not accomplishing pre1 means throwing a notPre1Exception instance.

Original source