-6

In other words, how are these two different?

try
{
    // Something that can throw an error
}
catch
{
    // Handle the error
}
finally
{
    // Something that runs after the try statement
}

vs.

try
{
    // Something that can throw an error
}
catch
{
    // Handle the error
}
// Something that runs after the try statement
Phoenix Logan
  • 1,238
  • 3
  • 19
  • 31

3 Answers3

2

finally block always executes.

You can be sure, that this block will be executed no matter what.

Literally it is something like:

Try something, catch some exceptions(if told to and if they are there) and execute the finally block finally.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • +1, But there *are* extreme cases where `finally` may not execute. See [Does the C# "finally" block ALWAYS execute?](http://stackoverflow.com/a/3216078/735425) – ssell Apr 16 '14 at 17:26
1

If there is a break in the try block or an exception, it may cause the program to halt. In cases like these code that is mandarory to be executed, like closing open connections and returning items to the connection pools are writen in the finally block. The finally block ensures that the code written inside it will be executed.

lds
  • 182
  • 1
  • 11
-1

If you only ever use general catches (i.e. catch without args or catch(Exception ex)), whether to put code in finally or after try/catch is basically a stylistic choice, as both a finally block and code after a try/catch will execute in any situation (barring deliberate escape mechanisms such as return).

However, if you use a narrow catch, and the exception isn't caught, what will happen is the finally block will still execute, however the code after the try/catch won't.

j.i.h.
  • 815
  • 8
  • 29
  • This is not true. Any form of flow control (`goto`, `continue`, `break`, `return`, `yield break`) would be able to bypass such a non-finally finally block. This would *only* protect you from `throw` as a flow control mechanism. – Servy Apr 16 '14 at 17:44
  • Yes, but that's not my point--my point is that the flow between following a `try/catch` block with a `finally` block will be the same as if you just put code after the `try/catch`, which I believe is what's confusing the questioner. The difference between using a `finally` or not arises when you use a narrower form of `catch()`. – j.i.h. Apr 16 '14 at 21:41