Show that OnOffSwitch.java can fail by throwing a RuntimeException inside the try block.
OnOffSwitch.java:22: unreachable statement
f();
Paul Mrozik wrote: Eckel was attempting to demonstrate the use of finally, which I hope I understand. No matter what kind of Exception is thrown, finally will execute and bring back an object to its intended state.
Paul Mrozik wrote:I honestly haven't the faintest idea why that worked, but it did. Thanks.
Jeff Verdegan wrote:The compiler could fail with the same unreachable code error, since it can tell that the if condition is always true, but it allows if (true) and if (false), presumably specifically for testing and debugging purposes.
As an example, the following statement results in a compile-time error:
because the statement x=3; is not reachable; but the superficially similar case:
does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.
The rationale for this differing treatment is to allow programmers to define "flag variables" such as:
and then write code such as:
The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.
Mike Simmons wrote:
Jeff Verdegan wrote:The compiler could fail with the same unreachable code error, since it can tell that the if condition is always true, but it allows if (true) and if (false), presumably specifically for testing and debugging purposes.
No, the compiler is not allowed to fail in this case. It's obeying the JLS, which specifically requires that an if statement be treated this way. Here's the explanation:
In reality, no one uses DEBUG like this anymore
Jeff Verdegan wrote:
Paul Mrozik wrote: Eckel was attempting to demonstrate the use of finally, which I hope I understand. No matter what kind of Exception is thrown, finally will execute and bring back an object to its intended state.
Correct.
When you have a finally block, then no matter how the try and catch portions complete--return, throw, break, continue, or normal completion--finally will be executed. That includes returning, throwing, etc. out of the catch blocks, not just the try.
~ Mansukh
Mansukhdeep Thind wrote:
One doubt Jeff - The return, continue, break keywords are intended to alter the flow control. Then why does the finally block still complete before any of these statements complete?
Consider Paul's rocket mass heater. |