Java Reference
In-Depth Information
Now that we have discussed the details of the
try
statement, we can discuss the
finally
keyword, which we use to create an optional block of code at the end of a
try
statement
that always executes after the code in the
try
block.
The
finally
Block
A
try
statement can be followed by a
fi nally block
. A
finally
block is a unique feature of
Java: it executes after a
try
statement, regardless of whether an exception occurs within the
try
block. A
finally
block can only appear after a
try
statement and must appear at the
end of the
catch
clauses. Figure 3.12 shows the syntax for a
finally
block.
The syntax of a
finally
block
FIGURE 3.12
A finally block can only
appear as part of a try
statement.
try {
//protected code
} catch (
exceptiontype identifier
) {
//exception handler
} finally {
//finally block
}
The finally block
always executes,
whether or not an
exception occurs
in the try block.
The finally keyword
A
finally
block allows you to perform any cleanup tasks that need to execute regardless
of what happens during the
try
block. For example, the following code closes a fi le after
attempting to read from it, whether or not the read is successful. Study the code carefully
and see if you can determine the output when no exception occurs:
1. import java.io.*;
2.
3. public class FinallyDemo {
4. public void readFromFile(String fileName) {
5. System.out.println(“Inside readFromFile”);
6. FileReader fis = null;
7. try {
8. fis = new FileReader(fileName);
9. char data = (char) fis.read();
10. System.out.println(“Just read: “ + data);
Search WWH ::
Custom Search