Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

amazing output for try/catch/finally? [duplicate]

Tags:

java

try-catch

I run this code :

public static void main(String[] args) {
    System.out.println(catcher());
}

private static int catcher() {
    try {
        System.out.println("TRY");
        thrower();
        return 1;
    } catch (Exception e) {
        System.out.println("CATCH");
        return 2;
    } finally {
        System.out.println("FINALLY");
        return 3;
    }
}

private static void thrower() {
    throw new RuntimeException();
}

and I expect to see this at output:

TRY
CATCH
FINALLY
2

but surprisingly the output is:

TRY
CATCH
FINALLY
3

I'm confused. where goes return 2 statement? Is return at finally a bad-practice?

like image 449
Taher Khorshidi Avatar asked Mar 05 '14 13:03

Taher Khorshidi


1 Answers

where goes return 2 statement?

It's gone.

Specifically what the JLS says is:

If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:

  • If the finally block completes normally, then the try statement completes abruptly for reason R.

  • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).

(A return statement is a cause for abrupt completion.)

Is return at finally a bad-practice?

Basically yes. Because there is no good reason for doing it and it will eat exceptions.

For example observe the following:

static void eatAnException() {
    try {
        throw new RuntimeException("oops");
    } finally {
        return;
    }
}

The return statement in finally discards the exception. Instead, place a return statement after a finally block.

like image 132
Radiodef Avatar answered Oct 18 '22 07:10

Radiodef