Java Reference
In-Depth Information
In this approach, notice that fin is initialized to null . Then, in the finally block, the file is
closed only if fin is not null . This works because fin will be non- null only if the file was
successfully opened. Thus, close( ) will not be called if an exception occurs while opening
the file.
It is possible to make the try / catch sequence in the preceding example a bit more
compact. Because FileNotFoundException is a subclass of IOException , it need not be
caught separately. For example, this catch clause could be used to catch both exceptions,
eliminating the need to catch FileNotFoundException separately. In this case, the standard
exception message, which describes the error, is displayed.
Ask the Expert
Q :
I noticed that read( ) returns -1 when the end of the file has been reached, but
that it does not have a special return value for a file error. Why not?
A : In Java, errors are handled by exceptions. Thus, if read( ) , or any other I/O method,
returns a value, it means that no error has occurred. This is a much cleaner way than
handling I/O errors by using special error codes.
In this approach, any error, including an error opening the file, will simply be handled
by the single catch statement. Because of its compactness, this approach is used by most
of the I/O examples in this topic. Be aware, however, that it will not be appropriate in cases
in which you want to deal separately with a failure to open a file, such as might be caused
if a user mistypes a file name. In such a situation, you might want to prompt for the correct
name, for example, before entering a try block that accesses the file.
Writing to a File
Search WWH ::




Custom Search