Public class test {
Public static void main (string [] ARGs ){
System. Out. println (demo ());
}
Static Boolean demo (){
Try {
Return true;
} Finally {
Return false;
}
}
}
You may think this program is illegal. After all, the demo-method cannot return both true and false. If you try it, you will find that it has no errors during compilation, and it prints false. Why?
The reason is that in a try-finally statement, the finally statement block is always executed when the control leaves the try statement block. This is the case whether the try statement block ends normally or unexpectedly. When a statement or block throws an exception, or executes a break or continue for a closed statement, or executes a return statement in a method like this program, it will end unexpectedly. They are called unexpected termination because they prevent the program from executing the following statements in order.
When both the try block and the Finally block end unexpectedly, the cause of the unexpected end in the try block will be discarded, the cause of the unexpected end of the try-finally statement block is the same as that of the finally statement block. In this program, the unexpected end caused by the Return Statement in the try statement block will be discarded, and the unexpected end of the try-finally statement is caused by the return in the finally statement block. In short, the program tries (try) to return (return) True, but the finally return (return) is false.
Dropping the cause of unexpected termination is almost never the behavior you want, because the initial cause of unexpected termination may be more important to program behavior. For programs that execute break, continue, or return statements in the try statement block, it is particularly difficult to understand the behavior of programs that are blocked by the finally statement block.
In short, each finally statement block should end normally unless an unchecked exception is thrown. Do not use a return, break, continue, or throw to Exit A finally statement block, and do not allow the propagation of a checked exception to a finally statement block.
If the try statement contains system. Exit (0) or system. In. Read ();, the finally statement is not executed! This problem is quite enjoyable!