Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The previous section showed you how to write an exception handler for thewriteList
method in theListOfNumbers
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 theListOfNumbers
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 further up the call stack to handle it.If the
writeList
method doesn’t catch the checked exceptions that can occur within it, thewriteList
method must specify that it can throw these exceptions. Let’s modify the originalwriteList
method to specify the exceptions that it can throw instead of catching them. To remind you, here’s the original version of thewriteList
method that won’t compile:To specify that// 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(); }writeList
can throw two exceptions, you add athrows
clause to the method declaration for thewriteList
method. Thethrows
clause comprises thethrows
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:Remember thatpublic void writeList() throws IOException, ArrayIndexOutOfBoundsException {ArrayIndexOutOfBoundsException
is a runtime exception, so you don’t have to specify it in thethrows
clause, although you can. You could just write this:public void writeList() throws IOException {
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.