Java Reference
In-Depth Information
Suppose we change line 28 to the following statement:
28. reader.readFromFile(“mydat.txt”);
Note that the fi lename is changed to
mydat.txt
. Assuming this fi le does not exist, a
FileNotFoundException
is thrown on line 8. Study the
FinallyDemo
program carefully
and try to determine its output when a
FileNotFoundException
is thrown on line 8. This
scenario is exactly the type of question that you will see on the certifi cation exam, and here
is the sequence of events that occurs:
1.
Line 5 displays
Inside readFromFile
.
2.
Line 8 throws a
FileNotFoundException
. Lines 9 and 10 do not execute.
3.
The exception is caught on line 11. Lines 12 and 13 execute. Line 14 also executes, but
the method does not immediately return.
4.
Control jumps to line 15 and the
finally
block executes.
5.
The
return
from line 14 now executes and the
readFromFile
method is popped off the
method call stack. Notice that line 23 does not execute.
6.
Control returns to
main
and line 28 executes.
Here is the output of the
FinallyDemo
program when a
FileNotFoundException
occurs:
Inside readFromFile
Handler for IOException
mydat.txt (The system cannot find the file specified)
Inside finally block
End of main
As you can see, a
finally
block is an interesting feature of Java. Typically, a
return
like
the one on line 14 of the
FinallyDemo
causes a method to immediately get popped off the
method call stack. However, because a
finally
block always executes, the return gets put
on hold until the
finally
block fi nishes.
A
try
-
finally
Statement
A
try
statement can contain a
finally
block without any
catch
clauses, as the following
class demonstrates. See if you can determine its output:
public class TryFinally {
public String go() {
System.out.println(“Inside go”);
String message = null;
try {
Search WWH ::
Custom Search