Nathan Bardon
Nathan Bardon

Reputation: 89

Why finally block exists?

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

Upvotes: 3

Views: 444

Answers (4)

Diriector_Doc
Diriector_Doc

Reputation: 610

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())

Upvotes: 1

Stijn Van Antwerpen
Stijn Van Antwerpen

Reputation: 1988

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.

Upvotes: 0

gahooa
gahooa

Reputation: 137302

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.

Upvotes: 1

Alexey Romanov
Alexey Romanov

Reputation: 170735

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.

Upvotes: 4

Related Questions