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 potentially throw an exception.try { Java statements }To construct an exception handler for the
writeList()
method from the ListOfNumbers 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.err.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 is said to govern the statements enclosed within it and defines the scope of any exceptions handlers (established by subsequentcatch
blocks) 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 either by one or morecatch
blocks, or onefinally
block.
Handling Errors using Exceptions |