Catching Exceptions

Consider the following code:

import java.util.Scanner;

public class Driver {
    public static void main(String[] args) {
        int[] list = {2, 4, 6};
        Scanner sc = new Scanner(System.in);
        int index = 0;

        while(index != -1) {
            System.out.println("Pick a number (or -1 to stop)");
            index = sc.nextInt();
            System.out.println(list[index]);
        }
    }
}

When run, if the user enters 3, an ArrayIndexOutOfBoundsException will be thrown causing the program to terminate.

Exceptions

Per our textbook (pp. 213), “An exception is an abnormal condition that arises in a code sequence at run time.  In other words, an exception is a run-time error.”

A Java Exception is an object that is created dynamically at runtime when some exceptional (not necessarily erroneous) condition occurs.  An Exception object can be thought of as a message that can be thrown (to avoid handling the exceptional condition) or caught (to handle the exceptional condition).

The Fix

To fix the original example we can simply put the code that accesses the array in a try-catch block and catch the Exception that occurs and handle it.

import java.util.Scanner;

public class Exceptions {
    public static void main(String[] args) {
        int[] list = {2, 6, 8, 1, 4, 9, 2, 5};
        Scanner sc = new Scanner(System.in);
        int index = 0;

        while(index != -1) {
            System.out.println("Pick a number (or -1 to stop)");
            index = sc.nextInt();

            try {
                System.out.println(list[index]);
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("Number out of bounds");  //continue
            }
        }
    }
}

We’ll cover exceptions in depth in CSCI-200.  What you have here should allow us to proceed and discuss reading and writing files.

© 2017 – 2019, Eric. All rights reserved.