Adding a finally Block Flashcards
What is the purpose of a finally block ?
The purpose of a finally block is to ensure that a given block of code is always executed whether an exception is thrown or not
Describe the 2 paths through code with both a catch and a finally block !
There are two paths through code with both a catch and a finally. If an exception is thrown, the finally block is run after the catch block.
If no exception is thrown, the finally block is run after the try block completes.
Give all the ways the exam is going to trick you !
The exam is going to try to trick you with missing clauses or with clauses in the wrong order :
25: try { // DOES NOT COMPILE
26: fall();
27: } finally {
28: System.out.println(“all better”);
29: } catch (Exception e) {
30: System.out.println(“get up”);
31: }
32: // DOES NOT COMPILE the catch and finally blocks are in the wrong order
33: try { // DOES NOT COMPILE
34: fall();
35: }
36:// does not compile because there must be a catch or finally block
37: try {
38: fall();
39: } finally {
40: System.out.println(“all better”);
41: } // catch is not required if finally is present.
Give a tricky example !
String s = “”;
try {
s += “t”;
} catch(Exception e) {
s += “c”;
} finally {
s += “f”;
}
s += “a”;
System.out.print(s);
The answer is tfa. The try block is executed. Since no exception is thrown, Java goes straight to the finally block.
Then the code after the try statement is run.
Give the one exception to the “finally block always runs after the catch block” rule !
The finally block doesn’t run at all, in case, we use the statement
“System.exit(0)” in the try or catch blocks