finally silently swallowing a return/exception from try
Same trap as Python's finally, expressed in Java: a return inside finally always wins, discarding
whatever the try block was about to return -- and if an exception was actively propagating out of try,
that exception is discarded too, with no trace. javac actually warns about this ([finally] finally clause cannot complete normally) -- one of the few warnings worth never suppressing.
static int returnOverride() {
try {
return 1;
} finally {
return 2; // silently discards the try's return value
}
}
static int swallowsException() {
try {
throw new RuntimeException("this exception vanishes without a trace");
} finally {
return 99; // the exception never propagates -- gone
}
}
System.out.println("finally overriding return: " + returnOverride());
System.out.println("finally swallowing an exception entirely: " + swallowsException());