问题
Why java switch statement can't handle null, since it has a "default" clause?
For example, if you have something like
switch(value){
case VAL1: do_something1(); break;
case VAL2: do_something2(); break;
default: do_something3();
}
shouldn't "default" deal with any other value, such as null?
回答1:
As always, it's in the JLS:
14.11. The
switch
StatementAll of the following must be true, or a compile-time error occurs:
- ...
- No switch label is
null
....
The prohibition against usingnull
as a switch label prevents one from writing code that can never be executed. If the switch expression is of a reference type, that is,String
or a boxed primitive type or an enum type, then a run-time error will occur if the expression evaluates tonull
at run time. In the judgment of the designers of the Java programming language, this is a better outcome than silently skipping the entireswitch
statement or choosing to execute the statements (if any) after thedefault
label (if any).
回答2:
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 which results in more boilerplate code.
Some would call this frustrating and unfortunate (myself included), where others will religiously disagree, maintaining that this is a "safer" decision.
For another 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 dilligently check all edge cases just to be allowed to treat them uniformly with the "normal" cases.
As a third notorious example, just look at the mess which the "language feature" of checked exceptions makes to your code.
回答3:
You can't SWITCH
on strings and other data types that can be null
. This behaviour has been changed in Java 7 to allow string-switches.
See this question for more info:
Why can't I switch on a String?
回答4:
This is by definition. I wouldn't lose too much time on this as it's in the specifications.
On the other hand I find this quite practical in fact, as in case of being null it doesn' have a primitive type associated, so we can't know how to handle it properly.
来源:https://stackoverflow.com/questions/19931408/why-java-switch-statement-cant-handle-null-since-it-has-a-default-clause