Handling Errors Using Exceptions |
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.ThePrintStream pstr; try { int i; System.out.println("Entering try statement"); pStr = new PrintStream( new BufferedOutputStream( new FileOutputStream("OutFile.txt"))); for (i = 0; i < size; i++) pStr.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.
Handling Errors Using Exceptions |