Using finally : Finally « Language Basics « C# / CSharp Tutorial






Sometimes you can define a block of code that will execute when a try/catch block is left.

The general form of a try/catch that includes finally is shown here:

try {
        // block of code to monitor for errors
    }
    catch (ExcepType1 exOb) {
        // handler for ExcepType1 
    }
    catch (ExcepType2 exOb) {
        // handler for ExcepType2 
    }
    .
    .
    .
    finally {
        // finally code
    }

The finally block will be executed whenever execution leaves a try/catch block.

using System; 
 
class MainClass { 
  public static void Main() { 
 
    Console.WriteLine("Receiving "); 
    try { 
      int i=1, j=0;
      
      i = i/j; 

    } 
    catch (DivideByZeroException) { 
      Console.WriteLine("Can't divide by Zero!"); 
      return; 
    } 
    catch (IndexOutOfRangeException) { 
      Console.WriteLine("No matching element found."); 
    } 
    finally { 
      Console.WriteLine("Leaving try."); 
    } 
  }   
  
}
Receiving
Can't divide by Zero!
Leaving try.








1.19.Finally
1.19.1.Using finally
1.19.2.finally block is always executed even if an exception was thrown in the try
1.19.3.Dispose a StreamWriter in finally block