Sunday, March 13, 2011

A simple class which has to deal with exception - ListOfNumbers

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.
// 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;

//Just add element to list


public ListOfNumbers () {
victor = new Vector(size);
for (int i = 0; i < size; i++)
victor.addElement(new Integer(i));
}
//Just write the list to some text file

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();
}
}

Upon construction, ListOfNumbers creates a Vector that contains ten Integer elements with sequential values 0 through 9. TheListOfNumbers 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.



  1. 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"));



  2. Tthe 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 ListOfNumbersinvokes elementAt:

    out.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 FileWriterconstructor, but does not display an error message about the exception thrown by elementAt.

 

This is because the exception thrown by the FileWriter constructor, IOException, is a checked exception and the exception thrown by the elementAt method,ArrayIndexOutOfBoundsException, is a runtime exception.

 

So what can be done here?


Java requires that you catch or specify only checked exceptions. For more information, refer to Java's catching or throwing exception.

No comments:

Post a Comment

Chitika