Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The first step in constructing an exception handler is to enclose the code that might throw an exception within atry
block. In general, atry
block looks like this:The segment in the example labaled code contains one or more legal lines of code that could throw an exception. (Thetry { code } catch and finally blocks . . .catch
andfinally
blocks are explained in following sections.)To construct an exception handler for the
writeList
method from theListOfNumbers
class, you need to enclose the exception-throwing statements of thewriteList
method within atry
block. There is more than one way to do this. You can put each line of code that might throw an exception within its owntry
block and provide separate exception handlers for each. Or, you can put all thewriteList
code within a singletry
block and associate multiple handlers with it. The following listing uses onetry
block for the entire method because the code in question is very short:If an exception occurs within the... 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)); } } catch and finally statements . . .try
block, that exception is handled by an exception handler associated with it. To associate an exception handler with atry
block, you must put acatch
block after it. The next section shows you how.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.