Java Reference
In-Depth Information
Notice that the preceding example closes the file stream after the try block that reads the
file has completed. Although this approach is occasionally useful, Java supports a variation
that is often a better choice. The variation is to call close( ) within a finally block. In this
approach, all of the methods that access the file are contained within a try block, and the
finally block is used to close the file. This way, no matter how the try block terminates,
the file is closed. Assuming the preceding example, here is how the try block that reads the
file can be recoded:
One advantage to this approach in general is that if the code that accesses a file terminates
because of some non-I/O-related exception, the file is still closed by the finally block. Al-
though not an issue in this example (or most other example programs) because the program
simply ends if an unexpected exception occurs, this can be a major source of trouble in lar-
ger programs. Using finally avoids this trouble.
Sometimes it's easier to wrap the portions of a program that open the file and access the
file within a single try block (rather than separating the two), and then use a finally block
to close the file. For example, here is another way to write the ShowFile program:
Search WWH ::




Custom Search