Java Reference
In-Depth Information
"+args[0]);
}
}
}
}
Note
Do not be concerned if you find this listing's file-oriented code difficult to
presentingthiscodeherebecausefilecopyingprovidesaperfectexampleofthefinally
block.
Listing 3-29
presents an application that copies bytes from a source file to a des-
tination file via a nested pair of try blocks. The outer try block uses a
java.io.FileInputStream
object to open the source file for reading; the inner
tryblockusesa
java.io.FileOutputStream
objecttocreatethedestinationfile
for writing, and also contains the file-copying code.
If the
fis = new FileInputStream(args[0]);
expression throws
FileNotFoundException
, execution flows into the outer try statement's
catch
(FileNotFoundException fnfe)
block, which outputs a suitable message to
the user. Execution then enters the outer try statement's finally block.
The outer try statement's finally block closes an open source file. However, when
FileNotFoundException
isthrown,thesourcefileisnotopen—noreferencewas
assignedto
fis
.Thefinallyblockuses
if (fis != null)
todetectthissituation,
and does not attempt to close the file.
If
fis = new FileInputStream(args[0]);
succeeds, execution flows
into the inner try block, which executes
fos = new FileOut-
putStream(args[1]);
.Ifthisexpressionthrows
FileNotFoundException
,
executionmovesintotheinnertry's
catch (FileNotFoundException fnfe)
block, which outputs a suitable message to the user.
This time, execution continues with the inner try statement's finally block. Because
thedestinationfilewasnotcreated,noattemptismadetoclosethisfile.Incontrast,the
opensourcefilemustbeclosed,andthisisaccomplishedwhenexecutionmovesfrom
the inner finally block to the outer finally block.
FileInputStream
's and
FileOutputStream
's
close()
methods throw
IOException
when a file is not open. Because
IOException
is checked, these