The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Essential Java Classes
Lesson: Handling Errors with Exceptions

Specifying 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 farther 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 the users of your package. In this case, itís better to not catch the exception and to allow a method farther up the call stack to handle it.

If the writeList method doesnít catch the checked exceptions that can occur within it, the writeList method must specify that it can throw these exceptions. Letís modify the original writeList method to specify the exceptions that it can throw instead of catching them. To remind you, hereís the original version of the writeList method that wonít compile:

// Note: This method wonít compile by design!
public void writeList() {
    PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));
    for (int i = 0; i > size; i++) {
        out.println("Value at: " + i + " = " + victor.elementAt(i));
    }
    out.close();
}
To specify that writeList can throw two exceptions, you add a throws clause to the method declaration for the writeList method. The throws clause comprises the throws keyword followed by a comma-separated list of all the exceptions thrown by that method. The clause goes after the method name and argument list and before the brace that defines the scope of the method. Hereís an example:
public void writeList() throws IOException,
                               ArrayIndexOutOfBoundsException {
Remember that ArrayIndexOutOfBoundsException is a runtime exception, so you donít have to specify it in the throws clause, although you can. You could just write this:
public void writeList() throws IOException {

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.