Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
This section shows you how to use the three components of an exception handler—thetry
,catch
, andfinally
blocks—to write an exception handler. The last part of this section walks through the example and analyzes what occurs during various scenarios.The following example defines and implements a class named
ListOfNumbers
. Upon construction,ListOfNumbers
creates aVector
that contains tenInteger
elements with sequential values 0 through 9. TheListOfNumbers
class also defines a method namedwriteList
that writes the list of numbers into a text file calledOutFile.txt
. This example uses output classes defined injava.io
, which are covered in the I/O: Reading and Writing (but no 'rithmetic) chapter.The first line in boldface is a call to a constructor. The constructor initializes an output stream on a file. If the file cannot be opened, the constructor throws an// Note: This class won�t compile by design! 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(); } }IOException
. The second line in boldface is a call to theVector
class�selementAt
method, which throws anArrayIndexOutOfBoundsException
if the value of its argument is too small (less than zero) or too large (larger than the number of elements currently contained by theVector
).If you try to compile the
ListOfNumbers
class, the compiler prints an error message about the exception thrown by theFileWriter
constructor. However, it does not display an error message about the exception thrown byelementAt
. The reason is that the exception thrown by the constructor,IOException
, is a checked exception and the one thrown by theelementAt
method,ArrayIndexOutOfBoundsException
, is a runtime exception. The Java programming language requires only that a program handle checked exceptions, so you get only one error message.Now that you�re familiar with the
ListOfNumbers
class and where the exceptions can be thrown within it, you�re ready to write exception handlers to catch and handle those exceptions.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.