Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The first step in constructing an exception handler is to enclose the statements that might throw an exception within atry
block. In general, atry
block looks like this:The segment of code labelled Java statements is composed of one or more legal Java statements that could throw an exception.try { Java statements }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 accomplish this task. You could put each statement that might potentially throw an exception within its owntry
statement, and provide separate exception handlers for eachtry
. Or you could put all of thewriteList
statements within a singletry
statement and associate multiple handlers with it. The following listing uses onetry
statement for the entire method because the code tends to be easier to read.ThePrintWriter out = null; try { System.out.println("Entering try statement"); out = new PrintWriter( new FileWriter("OutFile.txt")); for (int i = 0; i < size; i++) out.println("Value at: " + i + " = " + victor.elementAt(i)); }try
statement governs the statements enclosed within it and defines the scope of any exception handlers associated with it. In other words, if an exception occurs within thetry
statement, that exception is handled by the appropriate exception handler associated with thistry
statement.A
try
statement must be accompanied by at least onecatch
block or onefinally
block.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.