Handling Errors using Exceptions |
The two sections that cover catching an exception and declaring an exception, use this class as an example.This example defines and implements a class named ListOfNumbers. Upon construction, ListOfNumbers creates a Vector that contains ten Integer elements with the sequential values 0 through 9. The ListOfNumbers class also defines a method namedimport java.io.*; import java.util.Vector; class ListOfNumbers { private Vector victor; final int size = 10; public ListOfNumbers () { int i; victor = new Vector(size); for (i = 0; i < size; i++) victor.addElement(new Integer(i)); } public void writeList() { PrintStream pStr = null; 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)); pStr.close(); } }writeList()
which writes the list of numbers into a text file called "OutFile.txt".The
writeList()
method calls two other methods that can throw exceptions. First, this line:invokes the constructor for FileOutputStream which will thrown an IOException if the file cannot be opened for any reason.pStr = new PrintStream(new BufferedOutputStream(new FileOutputStream("OutFile.txt")));Second, the Vector class's
elementAt()
methodwill throw an ArrayIndexOutOfBoundsException 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 the Vector).pStr.println("Value at: " + i + " = " + victor.elementAt(i));If you try to compile the ListOfNumbers class, the compiler will print an error message about the exception thrown by the FileOutputStream constructor, but will not display an error message about the exception thrown by
elementAt()
. This is because the exception thrown by the FileOutputStream constructor, IOException, is a non-runtime exception and the exception thrown by theelementAt()
method, ArrayIndexOutOfBoundsException, is a runtime exception. Java only requires that you catch or declare non-runtime exceptions. For more information, refer to Java's Catch or Declare Requirement.The next section, Catching and Handling Exceptions, will show you how to write an exception handler for the ListOfNumbers's
writeList()
method.Following that is a section named Declaring the Exceptions Thrown By a Method will show you how to declare that the ListOfNumbers's
writeList()
method throws the exceptions instead of catching them.
Handling Errors using Exceptions |