Java Reference
In-Depth Information
11. }catch(IOException e) {
12. System.out.println(“Handler for IOException”);
13. System.out.println(e.getMessage());
14. return;
15. }finally {
16. System.out.println(“Inside finally block”);
17. try {
18. if(fis != null) {
19. fis.close();
20. }
21. }catch(IOException e) {}
22. }
23. System.out.println(“End of readFromFile”);
24. }
25.
26. public static void main(String [] args) {
27. FinallyDemo reader = new FinallyDemo();
28. reader.readFromFile(“mydata.txt”);
29. System.out.println(“End of main”);
30. }
31. }
Here is the sequence of events when
main
executes:
1.
A new
FinallyDemo
object is instantiated and its
readFromFile
is invoked on line 28.
2.
Line 5 displays
Inside readFromFile
, then line 6 declares a
FileReader
refer-
ence named
fis
. Notice that the
finally
block uses the
fis
reference, so it must be
declared outside the
try
block. This situation is common when writing
try
statements.
3.
We are assuming the
try
block executes successfully, so line 10 displays the first char-
acter from the file
mydata.txt
.
4.
Control jumps to the
finally
block on line 15.
Inside finally block
displays and
the file is closed on line 19. Notice the
close
method declares an
IOException
, so our
finally
block contains another
try
statement, a common situation in Java.
5.
Line 23 executes and
readFromFile
is popped off the method call stack.
6.
Control returns to
main
and
End of main
displays.
When no exceptions occur, the output of the
FinallyDemo
program is
Inside readFromFile
Just read: H
Inside finally block
End of readFromFile
End of main
Search WWH ::
Custom Search