A valid break statement in a try block

JLS 14.21 gives a description for someUnreachable statements

. Specifically, he says:

A valid break statement terminates the assertion if, within the target break, there are either no try statements whose try blocks contain a break statement, or there are try statements whose try blocks contain a break statement and any final statements of those attempting assertions can be executed normally.

I am trying to open this rule with an example. I wrote the following simple test program:

public static void main(String[] args) throws java.lang.Exception {
    while (true) {
        try {                      //Try statement which contains a break statement.
            break;
        } 
        finally {                //Finally always complete abruptly 
            throw new Exception(); //because of throwing an exception.
        }

        try {                      //Compile-time error: Unreachable statement
        } 
        finally {                //That finally doesn't contain any instruction. 
            //It always complete normally.
        }
    }
}

      

I don't think there is anything odd about this behavior, except that this exception is thrown in the following example:

public static void main(String[] args) throws java.lang.Exception {
    while (true) {
        try {
            break;
        } 
        finally {
            throw new Exception(); //Run-time error due to throwing an exception.
        }
    }
}

      

What is this rule?

+3


source to share


1 answer


If the flow of control is run on a try

part of the try

/ block finally

, then the part finally

will always execute. (This is very useful for immediately cleaning up resources when it would be unwise to rely on the garbage collector.)

The only exception is the call in the part try

that disables the JVM. For example System.exit(...)

.



In your case, the program flow can never reach the second try

, so the second is finally

also unreachable.

+1


source







All Articles