Monday 17 June 2013

Create and throw own exception

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Own_Exception
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Calculate c = new Calculate();
                c.calc();
            }
            catch (CountIsZeroException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
    public class CountIsZeroException : ApplicationException
    {
        public CountIsZeroException(string message) : base(message) { }
    }
    public class Calculate
    {
        public void calc()
        {
            Console.WriteLine("Enter the sum value");
            int sum = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter the count value"); //Enter the Zero("0")
            int count = Convert.ToInt32(Console.ReadLine());
            float average;
            if (count == 0)
            {
                throw (new CountIsZeroException("Zero count in Calculate"));
            }
            else
            {
                average = sum / count;
            }
        }
    }
}


Click me for source code