Exception handling (try/catch)

Computer Science · Java

Question 1 of 10

0

    What number does this Java code print? public class Main { public static void main(String[] args) { int x = 9; try { x = x / 3; x = x + 7; } catch (ArithmeticException e) { x = -8; } System.out.println(x); } }

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Exception handling (try/catch) explained

    An exception is an event that interrupts the normal flow of a program, such as dividing an integer by zero or reading a file that does not exist. In Java, a program can deal with an exception using try and catch. The risky code goes in the try block, and a catch block runs only if an exception of a matching type is thrown. Without handling, the program stops and reports the error.

    Exceptions are objects that belong to a class hierarchy. Those that extend RuntimeException, such as ArithmeticException, ArrayIndexOutOfBoundsException and NullPointerException, are unchecked, so the compiler does not force you to handle them. Checked exceptions, such as IOException, must either be caught or declared in the method signature with throws. A finally block runs after the try and any catch, whether or not an exception occurred, which makes it useful for cleanup such as closing a file.

    When several catch blocks are listed, Java checks them in order, so the more specific exception types must come first.

    int[] data = {10, 20, 30};
    try {
        System.out.println(data[3]);
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Bad index");
    } finally {
        System.out.println("Done");
    }
    

    Worked example

    Trace the code above.

    1. The array data has indexes 0, 1 and 2, so data[3] is out of range.
    2. Java throws an ArrayIndexOutOfBoundsException, and the rest of the try block is skipped.
    3. The matching catch block runs and prints Bad index.
    4. The finally block runs and prints Done.

    The output is "Bad index" and then "Done". Had the index been 2, nothing would be thrown, and the output would be 30 followed by Done.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What number does this Java code print?

      public class Main { public static void main(String[] args) { int x = 20; try { x = x / 2; x = x + 9; } catch (ArithmeticException e) { x = -3; } System.out.println(x); } }

    • Medium

      What number does this Java code print?

      public class Main { public static void main(String[] args) { int total = 7; boolean fail = false; try { total = total + 6; if (fail) { throw new IllegalStateException("boom"); } } catch (IllegalStateException e) { total = total * 3; } finally { total = total + 9; } System.out.println(total); } }

    • Hard

      What number does this Java code print?

      public class Main { public static void main(String[] args) { int[] data = {1, 5, 1}; int sum = 0; int errors = 0; for (int i = 2; i < 5; i += 1) { try { sum += data[i]; } catch (ArrayIndexOutOfBoundsException e) { errors++; } } System.out.println(sum); } }