Junior — Middle
What is the behavior of the program if an exception occurs in the finally block?
sobes.tech AI
Answer from AI
If a finally block in Java throws an exception, this exception "overrides" (replaces) any exception that might have been thrown in the try or catch blocks.
That is:
- If an exception was thrown in
tryorcatch, but an exception also occurs infinally, then the exception fromfinallywill be propagated further. - The previous exception from
tryorcatchis lost (it will not be propagated).
Example:
try {
throw new Exception("Exception from try");
} catch (Exception e) {
System.out.println("Handling exception");
} finally {
throw new RuntimeException("Exception from finally");
}
In this case, the program will throw a RuntimeException from finally, and the exception from try will be lost.
Therefore, it is recommended to avoid throwing exceptions from finally or handle them carefully.