Sobes.tech
Junior — Senior

How does the try‑catch‑finally chain work when an exception occurs

livecode

Task condition

Determine which output will appear in the console when executing the code fragment below. It is required to explain how the catch blocks, finally block, and rethrowing a new exception interact.

public static void main(String[] args) {
    try {
        int i = 1 / 0;
        System.out.println("1");
    } catch (ArithmeticException e) {
        System.out.println("2");
        throw new RuntimeException();
    } catch (Exception e) {
        System.out.println("3");
    } finally {
        System.out.println("4");
    }
    System.out.println("5");
}