1

I have a question for which I myself have a very intuitive answer. This question relates to the try-catch-finally blocks in Java. Well just the other day I was trying out something and I bumped into this compilation error. I have also gone through Do you really need the 'finally' block which answers lot of my doubts(especially comment #2).

What I am looking for here is why do I see a compilation error when I comment lines from #11 to #13(basically I am commenting the inner catch block). And the compilation and run-time execution runs fine when uncomment the same lines. If I could get an answer more from a OOPS context, it would increase my knowledge & will be of great help.

Thanks in advance. !!

public class TryCatchFinally {
  public static void main(String[] args) throws Exception {
    try {
        System.out.println("Try...");
        throw new Exception();          
    } catch (Exception e) {
        System.out.println("Catch...");
        try {
            System.out.println("Inner Try");
            throw new Exception();
        } /*catch(Exception e1) {//Line #11
            System.out.println("Inner catch");
        }*///Line #13
        finally{
            System.out.println("Inner finally");
        }
        System.out.println("Going out of catch..");//Line #17
    }
    finally{
        System.out.println("Finally");
    }
    System.out.println("Going out of try..");//Line #22
}}
Community
  • 1
  • 1
nitinram
  • 79
  • 5
  • what error do you see? – ergonaut Oct 29 '15 at 11:56
  • Since your code does `throw new Exception();`, which you never catch, the compiler is just telling that it is impossible to execute the two statements. – SomeJavaGuy Oct 29 '15 at 11:57
  • Unreachable code. The actual question is : When I uncomment the lines#11 to lines #13, I could successfully execute but when I comment those lines(i.e., inner catch block), why it fails.. ??!!!! – nitinram Oct 29 '15 at 11:59
  • Since you throw an exception in line#10 throw new Exception(); the rest of the code becomes unreachable and the compiler shows error for the same – Vivek Singh Oct 29 '15 at 11:59
  • because you throw an Exception you are not handling, which means it will still run finally, but then propagate the exception to the calling method – Stultuske Oct 29 '15 at 11:59
  • @NitinRamac because of `throw new Exception();`. the commented catch block handles this throw and wont stop the execution of the method. If you don´t have this catch block the throws definition of your main method will handle the exception and it will never be able to execute these two statements. At this point, if the exception is thrown, it will just execute the code in the finally block and will ignore the rest of the code. At this point your code is unreachable. – SomeJavaGuy Oct 29 '15 at 12:00
  • @KevinEsche Thanks for your response. So you mean to say finally in layman terms is a block in Java which is exclusively meant for the clean-up and as a good programming practice we should never catch/handle exceptions in finally. I hope even the Java compiler treats it the same way.. !!! – nitinram Oct 29 '15 at 12:07
  • @NitinRamac the finally block was neccessary if, for example, you would open a connection, do something with that connection, and would need to close it, no matter if you ran into an exception or not. since java 1.7, i guess, this is´t the prefered method because they introduced [try-with-ressources](http://stackoverflow.com/questions/17650970/am-i-using-the-java-7-try-with-resources-correctly). But it can still be used for everything that needs to be performed even if an exception occures. – SomeJavaGuy Oct 29 '15 at 12:11

3 Answers3

3

As others have observed, you throw an Exception on line 10. What happens after that?

With the inner catch block

When the inner catch block on lines 11-13 is uncommented, you'll throw the Exception on line 10 and immediately catch it. You'll print out "Inner catch", because that's what's in the catch block, then "Inner finally". The exception is no longer active since you caught it, so you proceed to line 17 and beyond.

Without the inner catch block

When the inner catch block is removed, you'll throw the Exception on line 10 and go straight to the finally block on line 14. But the exception hasn't been caught, so it's still active. When you exit the inner finally, there is no other catch block, so your method will return immediately and pass the exception up the call chain. (That's not very far in this case, since it's the main method.) The point is that the println on line 17 can never execute because of the exception.

The Java compiler is smart enough to figure out that there is no possible execution path through your program where line 17 gets executed, so so it gives you a compilation error for it (and for line 22, too).

And so

You don't need the inner catch if you don't need to do anything after your finally blocks. If you want to keep the method alive and execute something after your finally blocks, you need to keep the inner catch.

Erick G. Hagstrom
  • 4,873
  • 1
  • 24
  • 38
0

The last line of your inner try throws an exception, meaning only the finally blocks will be executed.

add another catch block, or remove that exception throw, and your problem is solved.

public class TryCatchFinally {
  public static void main(String[] args) throws Exception {
    try {
        System.out.println("Try...");
        throw new Exception();          
    } catch (Exception e) {
        System.out.println("Catch...");
        try {
            System.out.println("Inner Try");
            throw new Exception();
        } catch(Exception e1) {//Line #11
            System.out.println("Inner catch");
        }//Line #13
        finally{
            System.out.println("Inner finally");
        }
        System.out.println("Going out of catch..");//Line #17
    }
    finally{
        System.out.println("Finally");
    }
    System.out.println("Going out of try..");//Line #22
}}

or this

public class TryCatchFinally {
  public static void main(String[] args) throws Exception {
    try {
        System.out.println("Try...");
        throw new Exception();          
    } catch (Exception e) {
        System.out.println("Catch...");
        try {
            System.out.println("Inner Try");
           // throw new Exception();
        } /*catch(Exception e1) {//Line #11
            System.out.println("Inner catch");
        }*///Line #13
        finally{
            System.out.println("Inner finally");
        }
        System.out.println("Going out of catch..");//Line #17
    }
    finally{
        System.out.println("Finally");
    }
    System.out.println("Going out of try..");//Line #22
}}

will work.

Stultuske
  • 9,296
  • 1
  • 25
  • 37
0

At 10th line , You are throwing an exception which needs to be handled. Since you are not handling that exception , jvm is unable to compile the code after 10th line . That,s why jvm is giving the error "unreachable code" . So the solution is to either handle that exception by catching that exception or dont throw exception at 10th line.