/*
 * ListOfNumbers.java
 * Demo of exception handling in Java;
 * Example is based on an example from
 * http://java.sun.com/docs/books/tutorial/index.html
 */

import java.io.*;
import java.util.Vector;

public class ListOfNumbers extends Object {

    private static final int SIZE = 10;
    private Vector victor;
    
    /** Creates new ListOfNumbers */
    public ListOfNumbers() {
        victor = new Vector (SIZE);
        for (int i = 0; i < SIZE; i++) {
            victor.addElement(new Integer(i));
        }
    }
    
    /** Writes ListOfNumbers into a file "OutFile.txt */
    public void writeList() {
        PrintWriter out = null;
        
        try {
            System.out.println("Entering try block");

	    /* 
	     * can throw IOException, which should be either caught or declared,
	     * it is impossible for programmer to eliminate completely,
	     * possibility of I/O error 
	     */
            out = new PrintWriter(new FileWriter("OutFile.txt"));


	    /* 
	     * can throw ArrayIndexOutOfBoundsException, which nevertheless
	     * should not be declared.  It is also not necessary to use
	     * try/catch exception handling mechanism (with its associated
	     * runtime overhead) to handle this type of error. Programer can
	     * and must eliminate completely possibility of such errors.
	     */
            for (int i = 0; i < SIZE; i++) {               
                out.println("Value at: " + i + " = " + victor.elementAt(i));
            }

	// necessary
        } catch (IOException e) {
            System.err.println("Caught IOException: " + e.getMessage());

	// can be avoided 
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("Caught ArrayIndexOutOfBoundsException: "
		    + e.getMessage());
	// necessay
        } finally {
            if (out != null) {
                System.out.println("Closing PrintWriter");
                out.close();
            } else {
                System.out.println("PrintWriter not open");
            }
        }
        
    }
    
}
