|
|
Handling Errors with Exceptions |
The previous section showed you how to write an exception handler for thewriteListmethod in theListOfNumbersclass. 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 theListOfNumbersclass 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 to allow someone further up the call stack to handle it.If the
writeListmethod doesn't catch the exceptions that can occur within it, then thewriteListmethod must specify that it can throw them. Let's modify thewriteListmethod to specify the methods that it can throw. To remind you, here's the original version of thewriteListmethod:As you recall, thepublic 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)); }new FileWriter("OutFile.txt")statement might throw anIOException(which is not a runtime exception). Thevictor.elementAt(i)statement can throw anArrayIndexOutofBoundsException(which, as a subclass ofRuntimeException, is a runtime exception).To specify that
writeListthrows these two exceptions, you add athrowsclause to the method signature for thewriteListmethod. Thethrowsclause is composed of thethrowskeyword followed by a comma-separated list of all the exceptions thrown by that method. Thethrowsclause goes after the method name and argument list and before the curly bracket that defines the scope of the method. Here's an example:Remember thatpublic void writeList throws IOException, ArrayIndexOutOfBoundsException {ArrayIndexOutofBoundsExceptionis a runtime exception, so you don't have to specify it in thethrowsclause, although you can.
|
|
Handling Errors with Exceptions |