Next: Catching exceptions. Up: Exceptions. Previous: None.


What is an exception?

Textbook: Section 8.1

Sometimes a program will generate an exception while it is running, indicating that something unusual has occurred that constitutes a major problem. Generally, the program aborts with an error message describing the error. This process of generating an exception is called raising or throwing an exception.

Consider the following program that works with arrays.

import csbsju.cs160.*;

public class Example {
    public static void main(String[] args) {
        int[] arr = new int[2];
        for(int i = 0; i < 2; i++) arr[i] = IO.readInt();
        for(int i = 2; i >= 0; i--) IO.println(arr[i]);
    }
}
This program compiles fine. But when you run it, it would show something like the following.
1
2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
        at Example.main(Example.java:7)
What we see here is an error message indicating that an exception has been thrown.

This error message includes a lot of useful information. First, it says that there was an ArrayIndexOutOfBounds exception, indicating that the program attempted to accessed an array beyond its last index. Then it lists exactly where the computer was in the program at the time the exception was encountered: It was in the main() method of the Example class, specifically at line 7 in the file ``Example.java.'' All of this information is listed in the error message.

To get a better handle on what happened, we could go back to ``Example.java'' and find what's at line 7.

        for(int i = 2; i >= 0; i--) IO.println(arr[i]);
We know we accessed an array index off the end of some array. After inspecting this for a short while, we'll notice that this code accesses array index 2 of arr, which only has two elements in it (and hence its only valid indices are 0 and 1). This is what caused the exception.

Exceptions arise in many other circumstances.


Next: Catching exceptions. Up: Exceptions. Previous: None.