2

In PHP, JS and others, finally {} is there to be executed after try/catch, irrespective of an exception thrown or not. But isn't that just the function of all code after try/catch?

The two snippets should behave exactly the same:

try {
    throwException();
} catch () {
} finally () {
    executeMe();
}

and

try {
    throwException();
} catch () {
}

executeMe();
Zsolt Szilagyi
  • 4,741
  • 4
  • 28
  • 44
  • 4
    What if you rethrow or don't catch at all? – tkausl Jun 27 '19 at 11:02
  • 2
    In your second snippet, `executeMe()` wouldn't get executed if you're `return`ing in your `try` or in your `catch` block. It also won't get reached if you're re-throwing the exception (or another exception) in your `catch` block. With `finally`, it *will* be reached. – haim770 Jun 27 '19 at 11:04
  • So finally{} gets parsed even if I jumped out of the function with a return? Is the return then delayed, or is the finally executed after the return and without the methods/objects context? – Zsolt Szilagyi Jun 27 '19 at 11:05
  • 1
    finally will be executed with the context preceding the block whenever the try/catch block is being exited, even on a return – Aditya Jun 27 '19 at 11:07
  • This is for java language, but the behaviour is the same: https://stackoverflow.com/questions/3861522/do-you-really-need-the-finally-block – Valentino Jun 27 '19 at 11:47

1 Answers1

1

These comments add up to a nice answer:

In your second snippet, executeMe() wouldn't get executed if you're returning in your try or in your catch block. It also won't get reached if you're re-throwing the exception (or another exception) in your catch block. With finally, it will be reached. – haim770

So finally{} gets parsed even if I jumped out of the function with a return? Is the return then delayed, or is the finally executed after the return and without the methods/objects context? – Zsolt Szilagyi

finally will be executed with the context preceding the block whenever the try/catch block is being exited, even on a return – Aditya Jun

Zsolt Szilagyi
  • 4,741
  • 4
  • 28
  • 44