What correct exception throws the intended place out of reach?

For instance,

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 this question, please assume:

  • number is a private field in the class

  • This is an invariant of the class, which number should always be between 1 and 4; everything else indicates an error in this class. In other words, if an exception causes a trigger, it is never a caller's error, but it is always the authors of the classes.

What correct exception throws in this case?

+4
source share
4 answers

Edited

There is no good default CLR exception that is suitable for this situation. You have to roll yourself. I get directly from the exception, since you probably do not want this error to mix with other types of errors.

There are situations when a program can recover from this seemingly fatal situation: if you can be sure that the problem in this class cannot spread elsewhere. This is, for example, when you use this class as part of a function that has no side effects. This may seem like a far-fetched example, but itโ€™s not when you intentionally write or pack code so that it does not have side effects.

I donโ€™t think you should do something decisive, like quitting the program (as suggested in another now deleted answer). As a class author, this is not your responsibility.

As the author of software using this class, I would like to be able to tell the user that something happened, try to save backup copies, log data, write material to databases ... you will get an image.

+3
source

In Java, I would use AssertionError .

+2
source

Since the error is caused by a failed state, use an InvalidOperationException . If number was an argument to the called method, I would throw an ArgumentException .

+2
source

I would also add InvalidOperation and explain what went wrong.

I have all kinds of inner enumerations that should not be used by outer classes, but can be read. therefore, in the property set, I return InvalidOperation exceptions, this makes sense and is easy to find.

0
source

Source: https://habr.com/ru/post/1400881/


All Articles