Refresh . This is actually a great answer. On the other hand, maybe this is a good answer, because it illustrates a great finally example, succeeding where the developer (i.e. I) may not provide the proper cleanup. In the code below, consider a scenario in which an exception other than a SpecificException thrown. Then the first example will still perform the cleanup, while the second will not, although the developer might think: "I caught the exception and handled it, so of course the subsequent code will work."
Anyone who gives reason to use try / finally without catch . This might make sense with catch , even if you throw an exception. Consider case * where you want to return a value.
try { DoSomethingTricky(); return true; } catch (SpecificException ex) { LogException(ex); return false; } finally { DoImportantCleanup(); }
An alternative to the above without finally (in my opinion) is somewhat less readable:
bool success; try { DoSomethingTricky(); success = true; } catch (SpecificException ex) { LogException(ex); success = false; } DoImportantCleanup(); return success;
* I believe that the best example of try / catch / finally is when an exception is re-thrown (using throw , not throw ex , but this is a different topic) into the catch , and therefore finally needed as without it after try / catch will not work. This is usually done using the using statement on the IDisposable resource, but this is not always the case. Sometimes cleaning is not a Dispose call (or it is more than just a Dispose call).
Dan tao
source share