Java Reference
In-Depth Information
finally
{
try
{
fis.close();
}
catch (IOException ioe)
{
System.err.println("unable
to
close
"+sr-
cFile);
}
}
}
}
Listing3-30
providesanalternativeto
Listing3-29
thatattemptstobemorereadable.
It accomplishes this task by introducing a
copy()
method that uses a nested pair
of try-finally constructs to perform the file-copy operation, and also close each open
file whether an exception is or is not thrown. If the
FileInputStream fis
= new FileInputStream(srcFile);
expression results in a thrown
FileNotFoundException
, execution leaves
copy()
without entering the outer
trystatement.Thisstatementisonlyenteredafterthe
FileInputStream
objecthas
been created, indicating that the source file was opened.
Ifthe
FileOutputStream fos = new FileOutputStream(dstFile);
expression results in a thrown
FileNotFoundException
, execution leaves
copy()
withoutenteringtheinnertrystatement.However,executionleaves
copy()
onlyafterenteringthefinallyblockthatismatedwiththeoutertryblock.Thisfinally
block closes the open source file.
If the
read()
or
write()
method in the inner try statement's body throws an
IOException
object,thefinallyblockassociatedwiththeinnertryblockisexecuted.
This finally block closes the open destination file. Execution then flows into the outer
finally block, which closes the open source file, and continues on out of
copy()
.
Caution
Ifthebodyofatrystatementthrowsanexception,andifthefinallyblock
resultsinanotherexceptionbeingthrown,thisnewexceptionreplacesthepreviousex-
ception, which is lost.