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


Throwing exceptions

The throw statement

You can have your own code initiate an exception itself, using the throw statement.

throw new Exception("Hi there");
The throw statement is structured similarly to a return statement - you have the word throw, followed by an expression, followed by a semicolon.

In this case, we've created a new Exception object, using the constructor that takes a string as its parameter. This sets of the message returned by the exception's getMessage() method.

The throws clause

Throwing an exception from a method is useful when you want to indicate that the exception failed. Until now, we've been doing this via return values, but this is problematic: It reduces the number of possible return values. (For example, IO.readInt() will return Integer.MIN_VALUE if the user types a non-number. But this effectively disallows the user from typing the integer value Integer.MIN_VALUE also.) And it allows people to write programs where they might unintentially ignore a potential problem. (You've probably been ignoring this case with IO.readInt().)

When you write a method that might throw an exception, you must include a throws clause to make it clear to the compiler that you didn't just fail to catch the exception.

public class IntArray {
    private int[] arr;
    private int arr_elts;

    // other method definitions

    public int remove() throws Exception {
        if(arr_elts == 0) throw new Exception("array is already empty");
        --arr_elts;
        return arr[arr_elts];
    }
}

Actually, it's pretty rare that people write programs that throw Exception objects around. It's more frequent that they throw instances of other, more specific exceptions. The following alternative throws a NoSuchElementException object (defined in the java.util package)

import java.util.*;

public class IntArray {
    private int[] arr;
    private int arr_elts;

    // other method definitions

    public int remove() throws NoSuchElementException {
        if(arr_elts == 0) throw new NoSuchElementException("array is already empty");
        --arr_elts;
        return arr[arr_elts];
    }
}
Given this, then somebody who wants to catch the exception would catch a NoSuchElementException instead.
public static void run() {
    IntArray array = new IntArray();
    // : (omitting code that uses IntArray methods to add to array)

    try {
        array.remove();
    } catch(NoSuchElementException e) {
        System.err.println("could not remove: " + e.getMessage());
    }
}
(In fact, NoSuchElementException happens to be an unchecked exception, so catching it is optional.)


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