Test Finally Statement - CSharp Custom Type

CSharp examples for Custom Type:try catch finally

Description

Test Finally Statement

Demo Code

using System;/*  w w  w.j  a v a 2 s  .c om*/
class Tester
{
   public static void Main()
   {
      try
      {
         Console.WriteLine("Entering Main's try block");
         MyClass myObject = new MyClass();
         myObject.MethodA();
         myObject.MethodB();
         Console.WriteLine("Leaving Main's try block");
      }
      catch(Exception exObj)
      {
         Console.WriteLine("Entering Main's catch block");
         Console.WriteLine(exObj.Message);
         Console.WriteLine("Leaving Main's catch block");
      }
   }
}
class MyClass
{
   public void MethodA()
   {
      try
      {
         Console.WriteLine("Entering MethodA's try block");
         int myInt;
         int inputInt;
         Console.WriteLine("Opening file in MethodA");
         Console.Write("Please enter number: ");
         inputInt = Convert.ToInt32(Console.ReadLine());
         myInt = 10 / inputInt;
         Console.WriteLine("Leaving MethodA's try block");
      }
      catch(DivideByZeroException exObj)
      {
         Console.WriteLine("Entering MethodA's catch block");
         Console.WriteLine("Exception: " + exObj.Message);
         Console.WriteLine("Leaving MethodA's catch block");
      }
      finally
      {
         Console.WriteLine("Closing file in MethodA's finally block");
      }
      Console.WriteLine("Leaving MethodA");
   }
   public void MethodB()
   {
      try
      {
         Console.WriteLine("Entering MethodB's try block");
         int[] myArray = new int[10];
         Console.WriteLine("Opening file");
         //Index of bounds
         myArray[34] = 10;
         Console.WriteLine("Leaving MethodB's try block");
      }
      finally
      {
         Console.WriteLine("Closing file in MethodB's finally block");
      }
      Console.WriteLine("Leaving MethodB");
   }
}

Result


Related Tutorials