Deepankar Singh Deepankar Singh - 4 months ago 35
Java Question

Unreachable code- try-catch-finally

I know if java finds a line of code where it's guaranteed that control will never reach, then compiler reports unreachable code error.

consider following code.

static int method1() {

try{ return 1; }
catch(Exception e){ } // LINE-1
finally{ }
System.out.println("abc"); //LINE-2
return 2;

in above code

1 try block is guaranteed to exit by returning 1 but still lines after finally block (LINE-2 onwards) are reachable.

2. if i uncomment catch block (LINE-1), LINE-2 becomes unreachable.

Why is it so. Doesn't compiler able to see unconditional return in try block for case-1.


This is the relevant part of JLS 14.21:

A try statement can complete normally iff both of the following are true:

  • The try block can complete normally or any catch block can complete normally.

  • If the try statement has a finally block, then the finally block can complete normally.

In this case, although your try block can't complete normally, it has a catch block that can complete normally. The finally block can also complete normally.

The try statement is reachable and can complete normally, therefore the statement after it is reachable.

If you remove the catch block, the first bullet in the above quoted section is no longer true - which means the try statement can't complete normally, and the statement following it is unreachable.