Custom Exception in C#

Introduction:

Exception is a conditional that is caused by a run time error in the program. When C# compiler encounters an error such as dividing an integer by zero, it creates an exception object and throws it. If the exception object is not caught and handled properly the compiler will display an error message and will terminate the program

Here  program use to finally block, the last time of the output is produced by the finally block. A rule of thumb when creating our own exception classes is that we must implement all the three syastem.exception constructors as illustrated in the program. In program create a new type of user defined My Exception and it is being used to catch an exception with its own customized message. 

Example:

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

namespace CustomException
{
    public class MyCustomException :
        System.Exception
    {
        public MyCustomException(string txt)
            : base(txt)
        {
        }
    }
    class CustomExceptionExample
    {
        public void DisplayAll()
          {
              try
              {
                  Console.WriteLine(" Application started");
                  double a = 1000;
                  double b = 0;
                  Console.WriteLine("{0}/{2}",a,b,DivideVaues(a,b) );
                  Console.WriteLine("Error is handled in a try catch block and customised message
shown above."
);
              }
              catch(System.DivideByZeroException e)
              {
                  Console.WriteLine("\nDivideByZeroException Msg:{0}",e.Message);
              }
              catch(MyCustomException e)
              {
                  Console.WriteLine("\nMyCustomException Msg:{0}",e.Message);
              }
              finally
              {
                  Console.WriteLine("Application executed");
              }
          }
        public double DivideVaues(double a, double b)
        {
            if (b == 0)
            {
                MyCustomException e = new MyCustomException("cannot be divided by zero,result is
infinity."
);
                Console.WriteLine(e);
            }

            if (a == 0)
            {
                MyCustomException e = new MyCustomException("cannot have a zeroDivisor");
                Console.WriteLine(e);
            }
            return a / b;
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Example of customizes exception devloped in C#.");
            CustomExceptionExample cee = new CustomExceptionExample();
            cee.DisplayAll();
        }
    }
}

Output of the program:
custom.gif

Thank you. 

If you have any suggestions and comment about by blogs, please let me know.

Ebook Download
View all
FileInfo in C#
Read by 9.7k people
Download Now!
Learn
View all