Skip to main content
Logo image

Problem Solving with Algorithms and Data Structures using Java: The Interactive Edition

Section 1.13 Exception Handling

There are three types of errors that typically occur when writing programs. The first, known as a syntax error, simply means that the programmer has made a mistake in the structure of a statement or expression. For example, putting these arithmetic operators together:
jshell> int n = 2 + * 3;
|  Error:
|  illegal start of expression
|  int n = 2 + * 3;
|              ^
In this case, the Java compiler has found that it cannot complete the processing of this statement since it does not conform to the rules of the language. Syntax errors are usually more frequent when you are first learning a language.
Another type of error, known as a run time error, happens when the syntax is correct, but the program cannot execute correctly:
jshell> int n = 12 / 0;
|  Exception java.lang.ArithmeticException: / by zero
|        at (#1:1)
The last type of error, known as a logic error or semantic error, denotes a situation where the program executes but gives the wrong result. This can be due to an error in the underlying algorithm or an error in your translation of that algorithm. For example, the following code for computing the area of a rectangle uses correct Java syntax, and the arithmetic will not cause a run-time error, but the logic is wrong; area is length times width, not length plus width:
int length = 25;
int width = 15;
int area = length + width;
System.out.println(area);
In some cases, logic errors can lead to errors such as trying to divide by zero or trying to access an item in an array where the index of the item is outside the bounds of the array. In this case, the logic error leads to a runtime error that causes the program to terminate. These types of runtime errors are typically called exceptions.
Most of the time, beginning programmers think of exceptions as fatal runtime errors that cause the end of execution. However, most programming languages provide a way to deal with these errors that will allow the programmer to have some type of intervention if they so choose. In addition, programmers can create their own exceptions if they detect a situation in the program execution that warrants it.
When an exception occurs, we say that it has been thrown or raised. You can handle the exception that has been raised by using a try statement. For example, consider the following program that asks the user for an integer and then tries to access an array element at that index.
import java.util.Scanner;

class ArrayAccess {

    public static void main(String[] args) {
        int[] data = {10, 66, 47, 11, 505, 217};

        Scanner input = new Scanner(System.in);

        System.out.print("Enter an index: ");
        int index = input.nextInt();

        int value = data[index];
        System.out.format("The element is %d.%n", value);
    }
}
If the user enters a value that is less than the array length, the System.out.println() will display the value. However, if they enter a negative number or a number greater than or equal to the array length, the program will report an ArrayIndexOutOfBounds exception.
Enter an index: 7
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
  Index 7 out of bounds for length 6
        at ArrayAccess.main(ArrayAccess.java:13)
We can handle this exception by calling the System.out.format method from within a try block. A corresponding catch block “catches” the exception and prints a message back to the user in the event that an exception occurs. Here is the modified section of the code:
try {
    int value = data[index];
    System.out.format("The element is %d.%n", value);
}
catch (Exception ex) {
    System.out.format("Index must be from 0 to %d.%n",
        data.length);
    }
}
Now, if the user enters a number out of range, the program will catch the exception raised by the array access and will instead print a useful error message. This means that the program will not terminate but instead will continue on to the next statements.
The ex variable is an Exception object, and Java provides methods to allow programmers to extract information about the exception, such as an error message, the “stack trace” (the sequence of calls that happened when the exception occurred), and other information.
Enter an index: 7
Index must be from 0 to 6.
It is also possible for a programmer to cause a runtime exception by using the throw statement. For example, let’s say a method cannot calculate a valid return value if given a negative number. Instead of printing an error message—it will throw an IllegalArgumentException and let the code that callled the method handle it with a catch:
public static double doCalculation(double n) {
    if (n > 0) {
        // a complicated calculation goes here
        return ...;
    } else {
        throw new IllegalArgumentException(n + " cannot be negative.");
    }
  }
The string in the throw statement will be the message associated with the exception.
There are many kinds of exceptions that can be raised in addition to the ArrayIndexOutOfBoundsException shown above. See the Java API 1  for a list of some of the exception types.
You have attempted of activities on this page.