2

In most programming languages, there is a finally block that can be placed after try or catch block like this :

try {
    sensitiveFunction();
} catch (Exception e) {
    executedWhenFailed();
} finally {
    alwaysExecuted();
}

But we can execute the same code without finally block like that :

try {
    sensitiveFunction();
} catch (Exception e) {
    executedWhenFailed();
}

alwaysExecuted();

So, why does finally block exist? Anyone have an example that finally block is required ?

Thanks

4 Answers4

3

Even these examples aren't equivalent: if sensitiveFunction() throws something which doesn't extend Exception but Error instead, alwaysExecuted won't be executed without finally (please don't try to "fix" this by catching Throwable).

Or say executedWhenFailed() itself throws an exception: it's quite common to rethrow an exception from a catch block after adding some information. Again, alwaysExecuted() won't be executed in the second snippet.

Or suppose you have return sensitiveFunction(); instead of just a call. Etc. etc.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • Also, you don't usually catch *every* exception that might get thrown; only catch the ones you can do something about, or at least re-throw the ones you can't. – chepner Jul 19 '18 at 21:35
1

finally exists so that code can always be run, without regard to if you caught the exception or not.

Sometimes you want to just use try and finally together:

allocate()
try: 
   do_something_with_allocated()
finally:
   deallocate()

In the above example, it lets you 100% confidently clean up a resource that was opened above without regard for any exceptions that may be propagating up.

gahooa
  • 131,293
  • 12
  • 98
  • 101
0

If you throw a new exception in your catch block, you will eventually (after that exception has been handled) end up in your finally block. But not in the line after your catch.

Just throw an exception in executedWhenFailed, in your first example alwaysExecuted will be executed, in the second it wil not.

Stijn Van Antwerpen
  • 1,840
  • 17
  • 42
0

The finally block is executed even if there is a return statement in the catch() block.

(Example in JavaScript)

function foo() {
  try {
    throw "first"
  } catch(err){
    console.log(err)
    return "third"
  } finally {
    console.log("second") // Called before return in catch block
  }
  return "Never reached"
}

console.log(foo())
Diriector_Doc
  • 582
  • 1
  • 12
  • 28