|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The following example defines and implements a class namedListOfNumbers. The
ListOfNumbersclass calls two methods from classes in the Java packages that can throw exceptions.Upon construction,// Note: This class won't compile by design! // See ListOfNumbersDeclared.java or ListOfNumbers.java // for a version of this class that will compile. import java.io.*; import java.util.Vector; public class ListOfNumbers { private Vector victor; private static final int size = 10; public ListOfNumbers () { victor = new Vector(size); for (int i = 0; i < size; i++) victor.addElement(new Integer(i)); } 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(); } }ListOfNumberscreates aVectorthat contains tenIntegerelements with sequential values 0 through 9. TheListOfNumbersclass also defines a method namedwriteListthat writes the list of numbers into a text file calledOutFile.txt.The
writeListmethod calls two methods that can throw exceptions. First, the following line invokes the constructor for FileWriter, which throws an IOException if the file cannot be opened for any reason:out = new PrintWriter(new FileWriter("OutFile.txt"));Second, the
Vectorclass'selementAtmethod throws anArrayIndexOutOfBoundsException if you pass in an index whose value is too small (a negative number) or too large (larger than the number of elements currently contained by theVector). Here's howListOfNumbersinvokeselementAt:out.println("Value at: " + i + " = " + victor.elementAt(i));If you try to compile the
ListOfNumbersclass, the compiler prints an error message about the exception thrown by theFileWriterconstructor, but does not display an error message about the exception thrown byelementAt. This is because the exception thrown by theFileWriterconstructor,IOException, is a checked exception and the exception thrown by theelementAtmethod,ArrayIndexOutOfBoundsException, is a runtime exception. Java requires that you catch or specify only checked exceptions. For more information, refer to Java's Catch or Specify Requirement.The next section, Catching and Handling Exceptions, will show you how to write an exception handler for the
ListOfNumbers'writeListmethod.Following that, a section named Specifying the Exceptions Thrown By a Method will show you how to specify that the
ListOfNumbers'writeListmethod throws the exceptions instead of catching them.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.