What happens if a `try` block has a return statement? Does the `finally` block still execute?
If a try
block contains a return statement, the finally
block will still execute before the method actually returns. This happens because the finally
block is guaranteed to execute regardless of whether an exception is thrown or not.
However, if the finally
block also contains a return statement, it will override the return value from the try
block.
For example:
public int exampleMethod() {
try {
return 1;
} finally {
System.out.println("Finally block");
}
}
In this case, “Finally block” will be printed, and the method will return 1
. The finally
block always runs before the method returns.