Exception Propagation

Lab Java Intermediate 20 points

Method level3 throws RuntimeException("boom at N") when N is negative, otherwise returns N*2. level2 calls level3, level1 calls level2 and catches the exception, printing level1 caught: MESSAGE and returning 0. Read numbers and print each result.

Input

n, then n integers.

Output

One or two lines per number.

Example

Input

3
5
-2
0

Output

11
level1 caught: boom at -2
0
1
Sample input available Sample output available
Editor
Java

Hints

An uncaught exception travels up the call stack until a matching catch.

Solution explanation

Exceptions skip the rest of every method between the throw and the catch.

Show solution
import java.util.Scanner;

public class Main {
    static int level3(int n) {
        if (n < 0) {
            throw new RuntimeException("boom at " + n);
        }
        return n * 2;
    }

    static int level2(int n) {
        return level3(n) + 1;
    }

    static int level1(int n) {
        try {
            return level2(n);
        } catch (RuntimeException e) {
            System.out.println("level1 caught: " + e.getMessage());
            return 0;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            System.out.println(level1(sc.nextInt()));
        }
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD