Sobes.tech
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 try or catch, but an exception also occurs in finally, then the exception from finally will be propagated further.
  • The previous exception from try or catch is 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.

What is the behavior of the program if an exception… - sobes.tech