Friday, 15 March 2013

How to define an exception class ?

If we want to define an exception class we  need to adopt the following process:
  1. Define a class by inheriting from predefined class exception so that a new class is also an exception.
  2. Overwrite the message properly and provide the error message that has to be given when the exception occurred.
Add a new class DivideByOddNoException and  write the following code:

 
using System;

namespace CSharpConsole
{
    class DivideByOddNoException: Exception 
    {
        public override string Message
        {
            get
            {
                return "Attempted to divide by odd number ";
            }
        }
   }
}
 Add a new class ThrowDemo.cs and write the following code:

using System;

namespace CSharpConsole
{
    class ThrowDemo
    {
        static void Main()
        {
            int x, y, z;
            Console.Write("Enter x value ");
            x = int.Parse(Console.ReadLine());
            Console.Write("Enter y value ");
            y = int.Parse(Console.ReadLine());
            if (y % 2 > 0)
            {
                throw new DivideByOddNoException();
                //throw new ApplicationException("Divisor should not be an odd number ");
            }
            z = x / y;
            Console.WriteLine(z);
            Console.WriteLine("End of program ");
        }
    }
}

No comments:

Post a Comment