Previous | Next | Trail Map | Writing Java Programs | Handling Errors using Exceptions


Declaring the Exceptions Thrown by a Method

The previous section showed you how to write an exception handler for the writeList() method in the ListOfNumbers class. Sometimes, it's appropriate for your code to catch exceptions that can occur within it. In other cases, however, it's better to let a method further up the call stack handle the exception. For example, if you were providing the ListOfNumbers class as part of a package of classes, you probably couldn't anticipate the needs of all of the users of your package. In this case, it's better to not catch the exception and allow someone further up the call stack to handle it.

If the writeList() method doesn't catch the exceptions that can occur within it, then the writeList() method must declare that it can throw them. Let's modify the writeList() method to declare the methods that it can throw. To remind you, here's the writeList() method again.

public void writeList() {
    System.err.println("Entering try statement");
    int i;
    pStr = new PrintStream(
	      new BufferedOutputStream(
		 new FileOutputStream("OutFile.txt")));

    for (i = 0; i < size; i++)
	pStr.println("Value at: " + i + " = " + victor.elementAt(i));
}
As you recall, the new FileOutputStream("OutFile.txt") statement may throw an IOException (which is not a runtime exception). The victor.elementAt(i) statement can throw an ArrayIndexOutOfBoundsException (which is a subclass of RuntimeException).

To declare that writeList() throws these two exceptions, you would add a throws clause to the method signature for the writeList() method. The throws clause is composed of the throws keyword followed by a comma-separated list of all the exceptions thrown by that method. The throws clause goes after the method name and argument list and before the curly bracket that defines the scope of the method. Like this:

public void writeList() throws IOException, ArrayIndexOutOfBoundsException {
Remember that ArrayIndexOutOfBoundsException is a runtime exception, so you don't have to declare it in the throws clause, although you can.


Previous | Next | Trail Map | Writing Java Programs | Handling Errors using Exceptions