Suppose we have a method that accepts a value of an enumeration. After this method checks that the value is valid, it switches over the possible values. So the question is, what is the preferred method of handling unexpected values after the value range has been validated?
For example:
enum Mood { Happy, Sad } public void PrintMood(Mood mood) { if (!Enum.IsDefined(typeof(Mood), mood)) { throw new ArgumentOutOfRangeException('mood'); } switch (mood) { case Happy: Console.WriteLine('I am happy'); break; case Sad: Console.WriteLine('I am sad'); break; default: // what should we do here? }
What is the preferred method of handling the default case?
- Leave a comment like
// can never happen Debug.Fail()(orDebug.Assert(false))throw new NotImplementedException()(or any other exception)- Some other way I haven’t thought of
I prefer to
throw new NotImplementedException('Unhandled Mood: ' + mood). The point is that the enumeration may change in the future, and this method may not be updated accordingly. Throwing an exception seems to be the safest method.I don’t like the
Debug.Fail()method, because the method may be part of a library, and the new values might not be tested in debug mode. Other applications using that library can face weird runtime behaviour in that case, while in the case of throwing an exception the error will be known immediately.Note:
NotImplementedExceptionexists incommons.lang.