Have a look at this simple Java code:
final class A {
public static void main(String[] args) {
int x = 3;
boolean b;
switch(x) {
case 1:
b = true;
break;
default:
throw new RuntimeException();
}
System.out.println("b: " + b);
}
}
It assigns a b
a value in the switch, but in the default case, throws an exception. Of course in real code, x
would be computed in a more complex way.
$ javac A.java && java A
Exception in thread "main" java.lang.RuntimeException
at A.main(A.java:10)
Fails when it runs as expected.
One would like to factor this exception throwing into a function to avoid typing the same thing over and over:
final class A {
private static final void f() {
throw new RuntimeException();
}
public static void main(String[] args) {
int x = 3;
boolean b;
switch(x) {
case 1:
b = true;
break;
default:
f();
}
System.out.println("b: " + b);
}
}
However, this doesn't work:
$ javac A.java && java A
A.java:15: variable b might not have been initialized
System.out.println("b: " + b);
^
1 error
It's complaining that b
might not be initialized, even though it's clearly even though this is equivalent to the previous code. Why?