Middle — Middle+
If an exception occurs during division by zero in a method, and the catch block returns an error, and the finally block returns the string 'finally', what will the method return?
sobes.tech AI
Answer from AI
In Java, if a catch block returns a value and the finally block also contains a return statement, the value from finally will be returned by the method.
This is because the finally block always executes after try and catch, and if it contains a return, it overrides previous returns.
Example:
public String test() {
try {
int a = 1 / 0; // will throw ArithmeticException
} catch (ArithmeticException e) {
return "catch";
} finally {
return "finally";
}
}
// calling test() will return the string "finally"
Thus, even if an error is returned in catch, the method ultimately returns the value from finally — the string "finally".