c# - Is the finally block pointless? -


this question has answer here:

i'm teaching myself c# , studying try, catch , finally. book i'm using discussing how block runs regardless of whether or not try block successful. but, wouldn't code written outside of catch block run anyway if wasn't in finally? if so, what's point of finally? example program book providing:

class myappclass {     public static void main()     {         int[] myarray = new int[5];          try         {             (int ctr = 0; ctr <10; ctr++)             {                 myarray[ctr] = ctr;             }         }         catch         {             console.writeline("exception caught");         }                 {             console.writeline("done exception handling");         }         console.writeline("end of program");         console.readline();                 } } 

these scenarios finally useful:

try {     //do } catch (exception e) {     //try recover exception      //but if can't     throw e; } {     //clean } 

usually try recover exception or handle types of exceptions, if cannot recover of not catch specific type of exception exception thrown caller, finally block executed anyway.

another situation be:

try {     //do     return result; } {     //clean } 

if code runs ok , no exceptions thrown can return try block , release resources in finally block.

in both cases if put code outside try, never executed.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -