CSharp - Exception Custom Exception

Introduction

In an exception hierarchy, there are two major types of exception classes: SystemException and ApplicationException.

A SystemException is thrown by a runtime (CLR), and an ApplicationException is thrown by user programs.

When we create our own exception, the class name should end with the word Exception.

Demo

using System;

class ZeroDivisorException : Exception
{
    public ZeroDivisorException() : base("Divisor is zero") { }
    public ZeroDivisorException(string msg) : base(msg) { }
    public ZeroDivisorException(string msg, Exception inner) :
     base(msg, inner)
    { }/*w w w.  j  ava2  s .  c  o  m*/
}
class TestCustomeException
{
    int c;
    public int Divide(int a, int b)
    {
        if (b == 0)
        {
            //Ex.Message= "Divisor should not be Zero"
            throw new ZeroDivisorException("Divisor should not be Zero");
            //Ex.Message= "Divisor is Zero"
            //throw new ZeroDivisorException();
        }
        c = a / b;
        Console.WriteLine("Division completed");
        return c;
    }
}
class Program
{
    static void Main(string[] args)
    {
        int a = 10, b = 1, result;
        try
        {
            b--;
            TestCustomeException testOb = new TestCustomeException();
            result = testOb.Divide(a, b);
        }
        catch (ZeroDivisorException ex)
        {
            Console.WriteLine("Caught the custom exception: {0}",
              ex.Message);
        }
        finally
        {
            Console.WriteLine("\nExample completed");
        }
    }
}

Result