Previous | Next | Trail Map | Writing Java Programs | Handling Errors Using Exceptions


The ListOfNumbers Example (1.1notes)

The following example defines and implements a class named ListOfNumbers. The ListOfNumbers class calls two methods from classes in the Java packages that can throw exceptions.
import 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.out.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();
    }
}
Upon construction, ListOfNumbers creates a Vector that contains ten Integer elements with sequential values 0 through 9. The ListOfNumbers class also defines a method named writeList that writes the list of numbers into a text file called OutFile.txt.

The writeList method calls two methods that can throw exceptions. First, the following line invokes the constructor for FileOutputStream, which throws 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 method throws 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). Here's how ListOfNumbers invokes elementAt:

pStr.println("Value at: " + i + " = " + victor.elementAt(i));

If you try to compile the ListOfNumbers class, the compiler prints an error message about the exception thrown by the FileOutputStream constructor, but does not display an error message about the exception thrown by elementAt. This is because the exception thrown by the FileOutputStream constructor, IOException, is a checked exception and the exception thrown by the elementAt method, 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' writeList method.

Following that, a section named Specifying the Exceptions Thrown By a Method will show you how to specify that the ListOfNumbers' writeList method throws the exceptions instead of catching them.


Previous | Next | Trail Map | Writing Java Programs | Handling Errors Using Exceptions