There??™s one more option. After the try block and all the catch blocks, a programmer can add a finally block.
A finally block contains code that will always be executed, whether an error occurs or not. A finally block is
a good place to put general ???clean-up??? code, like the statement to close a data base.
Here is the syntax for the try/catch/finally construction:
try {
.
. //main line logic goes here
.
}
catch( SpecificException ex ) {
.
. //handle SpecificException
.
}
catch( LessSpecificException ex ) {
.
. //handle LessSpecificException
.
}
catch( Exception ex ) {
.
. //handle everything else that might happen
.
}
finally {
.
. //tidy up ??” this code will always be executed
.
}
//If code is successful, or exception is caught and
// handled, execution will continue here.
CHAP. 5] PROGRAMMING IN JAVA 87
Java??™s error-handling mechanism is one of its great strengths. Exception handling with try/
catch/finally is very robust and leads to very supportable code. Since one can easily add application-specific
exception classes to support one??™s own work, this approach is also very extendable.
INPUT AND OUTPUT
Java programs read and write data by means of streams. A stream is a series of data elements that flows
from some input device to the program, or from the program to some output device.
Pages:
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238