1

Hi I have a question about catch and finally. I looked around for the same case but had no luck but I'm sure this has been asked before.. so this may be a duplicate. Sorry for that. Anyway this is my question:

Here is a method which returns a boolean

public static boolean runtimeException() {
    try {
        int i = 1 / 0;
    } catch (ArithmeticException ae) {
        return true;
    } finally {
        return false;
    }
}

When I call this method in my main function:

public static void main(String[] args) {
    boolean flag = runtimeException();
    System.out.println(flag);
}

The result is: "false". Id like to know why this happens. I know that the finally block has to be executed at any means but logically the results don't make sense to me because the catch block is executed before and the function has already returned true. How can the function return false after already returning true?? Thanks in advance.

Micael Illos
  • 467
  • 2
  • 15
  • 2
    The finally block __always__ runs. If it has a return statement, that return will override any return statements in the try- or catch-block. – marstran Jul 09 '17 at 16:07
  • Have you considered reading the documentation? Why not? http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.2 – Lew Bloch Jul 09 '17 at 16:36

0 Answers0