Closing Files that Weren't Successfully Opened



Almost from as far back in my software education as I can remember,
people who would know have told me that it's good practice to close
one's files when one is done with them, so when I write programs that
open files I always try to do that. But I think I've found some grey
area that makes this policy a little ambiguous.

Whenever I write a program that uses the classes <File> and <Scanner>
to read in lines of text from a file, when I go to compile it my
compiler declares, "unreported exception
java.io.FileNotFoundException; must be caught or declared to be
thrown". And whenever I write a program that uses the classes
<FileWriter>, <BufferedWriter>, and <PrintWriter> to write lines of
text to a file, when I go to compile it my compiler gives a similar
declaration: "unreported exception java.io.IOException; must be caught
or declared to be thrown".

So, being pretty obedient to what the compiler tells me to do when I
can figure out what that is, I always add a <try-catch> block to
handle the mentioned exceptions.

My question is this. If I declare a variable <scnnr> to be of type
<Scanner>, and try to open it with the statement <scnnr = new
Scanner( new File( "Xy.Txt"))>, and a <FileNotFoundException> gets
thrown, should I still do a <scnnr.close()>, say in the <catch>
block? And similarly, if I declare <prntWrtr> to be of type
<PrintWriter> and try to open it with the statement <prntWrtr = new
PrintWriter( new BufferedWriter( new FileWriter( "Xy.Txt")))>, and an
<IOException> gets thown, should I still do a <prntWrtr.close()>, also
probably in the <catch> block? Or in each such situation can I
conclude that since an exception occurred while I was attempting to
open the respective file, the variables will still each both be
<null>, and therefore I don't have to do anything?

Kevin Simonson
.