In short, this design choice is in the spirit of Java.
The decision to throw an NPE when a switch expression evaluates to null
is along the lines of other decisions made in Java, which always prefer throwing an exception to silently handling the null
in the "obvious" way. The general rule seems to be that, when in doubt, the Java designers choose the option without default behavior. This has the side-effect of requiring boilerplate code at every use site.
Some would call this frustrating and unfortunate, but others disagree, maintaining that this is a safer decision.
For another potentially frustrating example see the enchanced for loop, which also throws an NPE if the collection is null
, instead of acting as if the collection was empty. There are many more examples in the JDK library, where the caller must check all edge cases just to be allowed to treat them uniformly with the "normal" cases.
As a third notorious example, Java's checked exceptions require a lot of boilerplate to handle at every level of call stack depth, and lure less experienced programmers into several antipatterns. The results are often swallowed exceptions, the same exception being reported several times in the log, exceptions getting non-uniform handling at the wrong level of abstraction, etc.