Please enable Javascript for better experience...
How to create custom exception class in c#
By Rahul Kumar Jha | Dec 3, 2014 | In Articles | Total Views [ 25235 ]
Taged In
(3 Like)
Rate

In this article I will try to explain, how can we create our own custom exception class to handle errors. We can create our own exception classes to handle errors as we need.

Introduction

Although there are already a lot of in-built exception classes to handle different types of errors like DivideByZeroException, ArgumentException, ArgumentOutOfRangeException, FormatException, NullReferenceException and many more except the base Exception class but still sometime we need our own custom exception class to handle few errors. In this article I will try to explain this with a simple example.

Using the Code

Creating a custom exception class is very easy and benefit of doing this is that we can put some custom code while handling errors through these classes. Let see this step by step for proper undstanding.

Step 1: Add custom exception class

To start with I have taken a console application and added a simple class and named it as CustomException and put it inside Exceptions folder for better understanding.

Step 2: Inherit from Exception class

Once class is added into solution, let's inherit it from Exception class. Please don't inherit from ApplicationException. Safer side is to inherit from Exception class as it is the base of all exception classes.

There are certain rules defined by microsoft which should be followed while making custom exception classes. Few of them are below:

  • Name your class with Exception suffix for easy naming convention.
  • Inherit your class from System.Exception or one of the other common base exceptions.
  • Don't inherit from ApplicationException class.
  • An exception must be serializable to work correctly across application domain and remoting boundaries.

For more detail please click this link-MSDN guidlines

Let put some code in exception class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace DotNetConceptCustomExceptionExample.Exceptions
{
    public class CustomException : Exception, ISerializable
    {
        public CustomException()
        {
            //put your custom code here
        }

        public CustomException(string message)
            : base(message)
        {
            //put your custom code here
        }

        public CustomException(string message, Exception innerException)
            : base(message, innerException)
        {
            Console.WriteLine("This is a demo code. You can write your own logic performing any valid activity.");
        }
        protected CustomException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            //put your custom code here
        }
    }
}

As you can see I have defined four constructor here but you don't need all. You can use any of them as per your need. I will use third one (with inner exeption). Though this I can see inner exeption also.

Step 3: Implementation

My final step would be to implement this in my code. To call my exception class I have written a method where I have written some logic to validate exception.

 static void Execute(int value)
        {
            if(value==0)
            {
                throw new CustomException("Value should not be equal to zero.", new InvalidOperationException());
            }
        }

Below is the full implementation.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetConceptCustomExceptionExample.Exceptions;

namespace DotNetConceptCustomExceptionExample
{
    class Program
    {
        static void Execute(int value)
        {
            if(value==0)
            {
                throw new CustomException("Value should not be equal to zero.", new InvalidOperationException());
            }
        }
        static void Main(string[] args)
        {
            try
            {
                int y = 5;
                int z = 0;
                Execute(z);
                int i = y / z;
            }
            catch (CustomException ex)
            {
                Console.WriteLine("Error found in application:" + ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error found in application:" + ex.Message);
            }
            Console.ReadLine();
        }
    }
}

Always take Exception as the last catch block as it is the base of all the child exception. It will through error if you write before any exception whether custom or in-build exception.

 catch (Exception ex)
            {
                Console.WriteLine("Error found in application:" + ex.Message);
            }

Hope it is little bit clear to you.

Share this

About the Author

Rahul Kumar Jha
Rahul Kumar Jha
Founder, Developer dotnet-concept.com

Public profile: user/profile/99900001


Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, ANGULAR, ANGULAR JS, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

User's Comments


 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment
 
 
 
 
 
 
Sponsors