46. What happens when you throw exception from finally block?

What happens when you throw exception from finally block?

When an exception is thrown from finally block, it will take precedence over exception thrown from try catch block

Example:

public class ExceptionInFinallyBlockExample {
public static void main(String[] args) {
try {
// This will throw an exception
throw new ArithmeticException(“Exception from try block”);
} catch (ArithmeticException e) {
System.out.println(“Caught in catch block: ” + e.getMessage());
// This will throw another exception
throw new NullPointerException(“Exception from catch block”);
} finally {
// This will throw an exception
throw new RuntimeException(“Exception from finally block”);
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *