Simple Try Catch - CSharp Custom Type

CSharp examples for Custom Type:try catch finally

Description

Simple Try Catch

Demo Code

using System;/*from  w w  w .  ja  v  a2s .  c  om*/
class MyClass
{
   public static void Main()
   {
      Console.WriteLine("Entering MyClass.Main");
      YourClass yourObject = new YourClass();
      yourObject.Method1();
      Console.WriteLine("Leaving MyClass.Main");
   }
}
class YourClass
{
   public void Method1()
   {
      Console.WriteLine("Entering YourClass.Method1");
      Method2();
      Console.WriteLine("Leaving YourClass.Method1");
   }
   public void Method2()
   {
      Console.WriteLine("Entering YourClass.Method2");
      int myInt = 0;
      int yourInt;
      try
      {
         Console.WriteLine("Entering try block");
         //Dividing by zero
         yourInt = 10 / myInt;
         Console.WriteLine("Leaving try block");
      }
      catch(DivideByZeroException exObj)
      {
         Console.WriteLine("Entering catch block");
         Console.WriteLine("Exception: " + exObj.Message);
         Console.WriteLine("Unable to automatically assign value to yourInt");
         Console.Write("Please manually enter number to be assigned yourInt: ");
         yourInt = Convert.ToInt32(Console.ReadLine());
         Console.WriteLine("Leaving catch block");
      }
      Console.WriteLine("Leaving YourClass.Method2");
   }
}

Result


Related Tutorials