c# - Where the finally is necessary? -


i know how use try-catch-finally. not advance of using finally can place code after try-catch block. there clear example?

update: not great answer. on other hand, maybe is answer because illustrates perfect example of finally succeeding developer (i.e., me) might fail ensure cleanup properly. in below code, consider scenario exception other specificexception thrown. first example still perform cleanup, while second not, though developer may think "i caught exception , handled it, surely subsequent code run."


everybody's giving reasons use try/finally without catch. can still make sense with catch, if you're throwing exception. consider case* want return value.

try {     dosomethingtricky();     return true; } catch (specificexception ex) {     logexception(ex);     return false; } {     doimportantcleanup(); } 

the alternative above without finally (in opinion) less readable:

bool success;  try {     dosomethingtricky();     success = true; } catch (specificexception ex) {     logexception(ex);     success = false; }  doimportantcleanup(); return success; 

*i think better example of try/catch/finally when exception re-thrown (using throw, not throw ex—but that's topic) in catch block, , finally necessary without code after try/catch not run. typically accomplished using statement on idisposable resource, that's not case. cleanup not dispose call (or more dispose call).


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -