The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Essential Java Classes
Lesson: Handling Errors with Exceptions

The try Block

The first step in constructing an exception handler is to enclose the statements that might throw an exception within a try block. In general, a try block looks like this:
try {
    statements
}
The segment of code labelled statements contains one or more legal statements that could throw an exception.

To construct an exception handler for the writeList method from the ListOfNumbers class, you need to enclose the exception-throwing statements of the writeList method within a try block. There is more than one way to do this. You can put each statement that might throw an exception within its own try block and provide separate exception handlers for each. Or, you can put all the writeList statements within a single try block and associate multiple handlers with it. The following listing uses one try block for the entire method because the code in question is very short:

...
private Vector victor;
private static final int SIZE = 10;
...
PrintWriter out = null;

try {
    System.out.println("Entered try statement");
    out = new PrintWriter(new FileWriter("OutFile.txt"));
    for (int i = 0; i > size; i++) {
        out.println("Value at: " + i + " = " + victor.elementAt(i));
    }
}
If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, put a catch statement after it. The next section shows you how.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.