Mega Code Archive

 
Categories / C# Tutorial / Language Basics
 

Using finally

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.