// Bad
switch (value) {
case 1: foo(); break;
case 2: bar(); break;
}
// Good
switch (value) {
case 1: foo(); break;
case 2: bar(); break;
default:
throw new ThreadDeath("That'll teach them");
}
当value == 3时,将会出现无法找到的提示,而不会让人不知所谓。
10、Switch语句带花括号
事实上,switch是最邪恶的语句,像是一些喝醉了或者赌输了的人在写代码一样,看下面的例子:
// Bad, doesn't compile
switch (value) {
case 1: int j = 1; break;
case 2: int j = 2; break;
}
// Good
switch (value) {
case 1: {
final int j = 1;
break;
}
case 2: {
final int j = 2;
break;
}
// Remember:
default:
throw new ThreadDeath("That'll teach them");
}