For example,
switch (number)
{
case 1: return DoOne();
case 2: return DoTwo();
case 3: return DoThree();
case 4: return DoFour();
default:
throw new ???Exception("Unexpected number encountered.");
}
For the sake of this question, please assume:
-
numberis a private field in a class -
It is a class invariant that
numbershould always be between 1 and 4; everything else indicates a bug in this class. In other words, if the exception triggers, it is never the caller’s fault but always the class’s author’s.
What is the correct exception to throw in this case?
Edited
There is no good default CLR exception that fits this situation. You should roll your own. I’d derive directly from exception, as you probably don’t want this error to get mixed up with other types of errors.
There are situations where a program can recover from this seemingly unrecoverable situation: If you can be sure that the problem in this class can not spread to elsewhere. This is for instance when you use this class as part of a function that has no side effects. This may seem a contrived example, but it isn’t when you purposely write or package code such that it is free from side effects.
I don’t think you should do something drastic like exiting the program (as suggested in another now deleted answer). As a class author that is not your responsibility.
As an author of the sofware using this class, I would like to get the opportunity to tell the user that something bad happend, try to save backups, log information, write stuff to databases…. you get the picture.