How to handle exceptions at Class constructor level in C#.Net


We need to do check possible condition and throw the exception from constructor level. Please go through below example for your reference.

This is one of the best c#.net interview question.


using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int a = 1, b = 0;
                Paramater obj = new Paramater(a, b);
                Console.Read();
            }
            catch(Exception ex)
            {
                Console.Write(ex.Message);
                Console.Read();
            }
        }
    }

    class Paramater
    {
        int result;
        public Paramater(int a, int b)
        {
            if (b == 0)
                throw new DivideByZeroException("Class:Parameter, from constructor while b==0");
            result = a / b;
        }
    }
}

Output:

If you have any queries or suggestions, please feel free to ask in comments section.
Share this post :

Post a Comment

Please give your valuable feedback on this post. You can submit any ASP.NET article here. We will post that article in this website by your name.

 
Support : Ranga Rajesh Kumar
Copyright © 2012. ASP.NET Examples - All Rights Reserved
Site Designed by Ranga Rajesh Kumar