C# Program for User Defind Exception – Example

Below is an example for user defined exception in csharp …….
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    public class negativeexception : ApplicationException
    {
        public negativeexception()
        {
        }
        public negativeexception(string s)
            : base(s)
        {
            Console.WriteLine(“It’s a user defined Exception”);
        }
    }
    public class negative
    {
        int sum = 12;
        int count = 3;
        public void negativecount()
        {
            if (count < 0)
            {
                throw new negativeexception(” Negative exception”);
            }
            else
            {
                int average = sum / count;
                Console.WriteLine(“Average is:{0}”, average);
            }
        }
    }
    public class arithmetic
    {
        public static void Main(string[] args)
        {
            negative obj = new negative();
            try
            {
                obj.negativecount();
            }
            catch (negativeexception e)
            {
                Console.WriteLine(“Negative exception:{0}”, e);
            }
            Console.ReadLine();
        }
    }
}

Add Comment