Java Reference
In-Depth Information
< Day Day Up >
Puzzle 36: Indecision
This poor little program can't quite make up its mind. The
decision
method returns
true
. But it
also returns
false
. What does it print? Is it even legal?
public class Indecisive {
public static void main(String[] args) {
System.out.println(decision());
}
static boolean decision() {
try {
return true;
} finally {
return false;
}
}
}
Solution 36: Indecision
You might think that this program is illegal. After all, the
decision
method can't return both
TRue
and
false
. If you tried it, you found that it compiles without error and prints
false
. Why?
The reason is that
in a
try-finally
statement, the
finally
block is always executed when
control leaves the
try
block
[JLS 14.20.2]. This is true whether the
try
block completes normally
or
abruptly
. Abrupt completion of a statement or block occurs when it throws an exception,
executes a
break
or
continue
to an enclosing statement, or executes a
return
from the method as
in this program. These are called abrupt completions because they prevent the program from
executing the next statement in sequence.
Search WWH ::
Custom Search