Reputation: 294
I have two code snippets in both I return from try and have finally block too.The first one works fine and prints from finally too and later gives compile time error at line marked line1.
1st snippet
class abc {
public static void main(String args[]) {
System.out.println("1");
try {
return;
} catch (Exception ex) {
System.out.println("Inside catch");
} finally {
System.out.println("2");
}
System.out.println("3");
}
}
2nd snippet(Compile Time Error)
class Test11 {
public static void main(String[] args) {
Test11 test = new Test11();
System.out.println("1");
try {
return;
} finally {
System.out.println("2");
}
// COMPILER ERROR
// System.out.println(test instanceof Test11);// line 1
}
}
Answer: The reason being in the 1st snippet there is a path of execution followed by catch block but in 2nd snippet there is no such path so statement after finally is unreachable.
Upvotes: 4
Views: 122
Reputation: 716
line 1 is unreachable statement. Because there is no possibly to go to line1.
if Exception trows it will break inside try. if not return from method.
if catch block is there, it make sure if exception happen in try block it will goto line 1
Upvotes: 1