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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With