In the first example, you can throw an exception again, and the code inside finally will still execute. This would be impossible in the second example.
If you decide not to throw the exception, then yes, there is a slight difference. However, this is considered a bad form - very rarely you need to use an exception that cannot be explicitly handled .
This is a keyword that will help you with the flow of code. When you throw an exception, it affects the flow of code (for example, using return ), the finally keyword allows you to express that when an exception occurs (or you return from try ) you still need execution to do something, because it leaves.
To answer the question annoyingly, it is necessary when you need it, and not when you do not.
additional literatureTo be safe, before you try to start using this keyword, read it:
http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx
And the keywords for exception handling in general:
http://msdn.microsoft.com/en-us/library/s7fekhdy.aspx
<Strong> Examples
Catch an exception to do something with it, and then re-throw it. Use finally to invoke any code:
try { OpenConnectionToDatabase(); // something likely to fail } catch (Exception ex) { Log(ex); throw; // throw ex; // also works but behaves differently } // Not specifying an exception parameter also works, but you don't get exception details. //catch (Exception) //{ // Log("Something went wrong); // throw; //} finally { CloseConnectionToDatabase(); }
Do not register interest in catching exceptions, but use finally to organize the code:
try { OpenConnectionToDatabase(); // something likely to fail } finally { CloseConnectionToDatabase(); }
Come back from your try because it looks well formatted, but still use finally to arrange the code:
try { OpenConnectionToDatabase(); return 42; } finally { CloseConnectionToDatabase(); }