Java Reference
In-Depth Information
527
ANSWERS TO SELF-CHECK QUESTIONS
1.
When the
PrintWriter
object is created, the output file is emptied.
Sadly, that is the same file as the input file. The input file is now empty and
the
while
loop exits immediately.
2.
The program throws and catches a
FileNotFoundException
, prints
an error message, and terminates.
3.
Throw an exception if the amount being deposited is less than zero.
4.
The balance is still zero because the last statement of the
withdraw
method was never executed.
5.
The specification throws
IOException
is sufficient because
FileNotFound-Exception
is a subclass of
IOException
.
6.
Because programmers should simply check for
null
pointers instead of
trying to handle a
NullPointerException
.
7.
The
FileReader
constructor succeeds, and in is constructed. Then the
call
in.next()
throws a
NoSuchElementException
, and the
try
block is aborted. None of the catch clauses match, so none are executed. If
none of the enclosing method calls catch the exception, the program
terminates.
8.
NoÈŒyou catch both exception types in the same way, as you can see from
the code example on page 508. Recall that
IOException
is a checked
exception and
NumberFormatException
is an unchecked exception.
9.
If it had been declared inside the
try
block, its scope would only have
extended to the end of the
try
block, and the
finally
clause could not
have closed it.
10. The
FileReader
constructor throws an exception. The
finally
clause
is executed. Since
reader
is
null
, the call to
close
is not executed.
Next, a
catch
clause that matches the
FileNotFoundException
is
located. If none exists, the program terminates.