Adding a finally Block Flashcards

1
Q

What is the purpose of a finally block ?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Describe the 2 paths through code with both a catch and a finally block !

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Give all the ways the exam is going to trick you !

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Give a tricky example !

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Give the one exception to the “finally block always runs after the catch block” rule !

A

The finally block doesn’t run at all, in case, we use the statement
“System.exit(0)” in the try or catch blocks

How well did you know this?
1
Not at all
2
3
4
5
Perfectly