Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing NotImplementedException on default case in switch statement

Should I throw a NotImplementedException() on default, if I have cases for all possible enum types?

like image 447
JamesBrownIsDead Avatar asked Nov 10 '09 17:11

JamesBrownIsDead


People also ask

Can we write two defaults in switch case?

There can be at most one default statement. The default statement doesn't have to come at the end. It may appear anywhere in the body of the switch statement. A case or default label can only appear inside a switch statement.

Can switch case throw exception in Java?

If an exception occurs inside the switch, then it's fine. The one reasonably standard place you might throw inside a switch statement is in the default case. If reaching that case indicates invalid input, then it's reasonable to throw an exception.

Does default always run in a switch statement?

The default case is always run last, no matter where it appears.


1 Answers

If you're looking for a value that must, by definition, correspond to the value of an enumeration, and you've received something else, that's definitely an invalid argument.

But now you have to consider the context.

Is the method private, and only accessible by members of your class library or application? If it is, it's a coding error that shouldn't EVER occur in the first place. Assert and fail.

If, on the other hand, it's a public or protected method, and can be accessed by clients consuming your library, you should definitely throw with a meaningful message (and preferably a well-known exception type).

It's important to remember that enumerations are not range-checked in the Framework. I may specify that a method requires a parameter of type Environment.SpecialFolder; but it will accept any 32-bit integer value.

So, in short, if your method is for public consumption, yes, by all means, throw. If it's not for public consumption, Assert.

like image 105
Mike Hofer Avatar answered Oct 19 '22 23:10

Mike Hofer