Search code examples
parsingreturnblockfinallyunreachable-code

Unrechable Statement if return Statement in Finally Block


public class UnrechableCode {
        public static void main (String args[])
        {
            UnrechableCode uc=new UnrechableCode();
            try
            {
               System.out.println(1/0);
            }
            catch(Exception e)
            {
                System.out.print("Inside Catch");
                return ;
            }
            finally
            {
                 System.out.println("Inside Finally");
                 //return;
            }
            System.out.println("TEST");
        }
}

In Above Code When remove return Statement from Catch then the Statement after finally Block is not Executed,but it is reachable by parser. in the same scenario if i write return in finally block same statement is unreachable by parser,so if in the previous case statement is reachable by parser why statement is not executing.?


Solution

  • The Java compiler has only a limited capability to predict whether a particular line of code in a program can ever be reached. This fact is not a fault of the designers of Java; it is a proven fact that it is not possible to predict the behavior of all possible programs of a general-purpose language so completely. The only choice the designers of Java could make is in just how limited this capability of the compiler should be.

    See Why does Java have an "unreachable statement" compiler error? for a discussion of why the compiler has this ability at all, why it considers "unreachable code" an error, and why some things that could (relatively easily) have been detected as "unreachable code" are not considered to be "unreachable code" errors by the compiler.

    In your particular case, the fact that 1/0 will always throw an exception, together with the fact that there is a return in the catch block that catches the exception, will prevent any execution of the program from ever writing "TEST" to the output. But the Java compiler does not try to account for exceptions thrown by such things as 1/0 when it looks for unreachable code. Therefore it acts as if there were a possible control path that executed the try block, did not throw an exception (so did not execute any code in the catch block), then executed the finally block and then the code after the finally block.

    One of the things that the compiler does consider is that the finally block will always execute before the code that follows it, and that if there is a return in the finally block, the code after the return will not execute at all. Therefore a return in the finally block will make the code after it unreachable.

    TL;DR: In one case, the "TEST" statement is unreachable for reasons that the Java compiler is designed to recognizes; in the other case, the "TEST" statement is unreachable for reasons that the Java compiler is not designed to recognize.