public class Test2 {
public static void main(String args[]) {
System.out.println(method());
}
public static int method() {
try {
throw new Exception();
return 1;
} catch (Exception e) {
return 2;
} finally {
return 3;
}
}
}
in this problem try block has return statement and throws exception also…
its output is COMPILER ERROR….
we know that finally block overrides the return or exception statement in try/catch block…
but this problem has both in try block…
why the output is error ?
Best Answer
Because your
return
statement is unreachable - the execution flow can never reach that line.If the
throw
statement was in anif
-clause, then thereturn
would be potentially reachable and the error would be gone. But in this case it doesn't make sense to havereturn
there.Another important note - avoid returning from the
finally
clause. Eclipse compiler, for example, shows a warning about a return statement in thefinally
clause.