14

When should I use code snippet A instead of snippet B (i.e. what are the benefits of using snippet A)?:

Snippet A:

try {
    // codeblock A
}
catch (Exception ex) {
    // codeblock B
}
finally {
    //codeblock C
}

Snippet B:

try {
    // codeblock A
}
catch (Exception ex) {
    // codeblock B
}

//codeblock C
poplitea
  • 3,585
  • 1
  • 25
  • 39

5 Answers5

15

Use a finally block if you have code that must execute regardless of whether or not an exception is thrown.

Cleaning up scarce resources like database connections are a good example.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • It's also good practice because it explicitly states what is going on, e.g. regardless of execution we must free resource x, etc. – Tony Sep 13 '11 at 17:10
  • Note, in Java 7 you can use a try-with-resources statement to close certain resources, so you wouldn't need a `finally` in this case. – dogbane Sep 13 '11 at 17:13
  • 1
    @duffymo But wouldn't `codeblock C` in _snippet B_ also take care of this? – poplitea Sep 13 '11 at 17:22
  • 2
    Not guaranteed if someone puts a return in the catch block. – duffymo Sep 13 '11 at 17:23
3

An obvious case is when you re-raise or throw another exception in your catch block.

a1ex07
  • 36,826
  • 12
  • 90
  • 103
1

It's useful if you need to do some cleanup, e.g. close a database connection. Because "finally" is executed always, you don't need to do the bug-prone copy-paste of the same code in the end of the "try" and in also in one or more "catch" blocks.

TotoroTotoro
  • 17,524
  • 4
  • 45
  • 76
1

You must almost always use the snippet with finally block when you have resources that needs clean up in both successful or error scenarios. A typical example is the jdbc connection object which should always be closed (clean up) in the finally block.

Scorpion
  • 3,938
  • 24
  • 37
0

Imagine to have a return statement inside the catch block: the C block will not be executed in snippet B, but in snippet A it will, before returning.

spongebob
  • 8,370
  • 15
  • 50
  • 83