Custom Exception in C#

Creating Custom Exception in C# with examples

In this article, I am going to discuss how to create a Custom Exception in C# with examples. Please read our previous article before proceeding to this article where we discussed how to implement Multiple Catch Blocks in C# with some examples. As part of this article, we are going to discuss the following pointers in detail.

  1. What are System Exceptions and Application Exceptions in C#?
  2. What are the different ways to create a custom exception in C#?
  3. Why do we need to create custom exceptions in C#?
  4. Examples of creating custom Exceptions in C#.

In C#, the exceptions are divided into two types such as

  1. System exception
  2. Application exception
What are System Exceptions in C#?

An exception that is raised implicitly under a program by the exception manager because of some logical mistakes (some predefined conditions) is known as system exception. For example:

  1. DivideByZeroException
  2. IndexOutOfRangeException
  3. FormatExceptionetc

An exception that is raised explicitly under a program based on our own condition (i.e. user-defined condition) is known as the application exception.

What are Application Exceptions in C#?

An exception that is raised explicitly under a program based on our own condition (i.e. user-defined condition) is known as an application exception. As a programmer, we can raise application exception at any given point of time. To raise an application exception we need to adopt the following process

Create Custom Exception in C#

While creating and throwing an object of Exception class we should not use system exception classes like DivideByZeroException, FormatException, etc.

What are the Different Ways to Create Custom Exception in C#?

To create and throw an object of exception class by us, we have two different options.

  1. Create the object of a predefined Exception class where we need to pass the error message as a parameter to its constructor and then throw that object so that whenever the exception occurs the given error message gets displayed.
  2. Define a new class of type exception and throw that class object by creating it.
To define an exception class of our own we have to follow two steps

Step1: Define a new class inheriting from the predefined class Exception so that the new class also acts as an Exception class.

Step2: Now override the virtual property message with the required error message.

Let us understand how to create a custom exception in C# with an example:

Example1: Creating and throwing a custom exception in C#
namespace ExceptionHandlingDemo
{
    //Creating our own Exception Class by inheriting Exception class
    public class OddNumberException : Exception
    {
        //Overriding the Message property
        public override string Message
        {
            get
            {
                return "divisor cannot be odd number";
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int x, y, z;
            Console.WriteLine("ENTER TWO INTEGER NUMBERS:");
            x = int.Parse(Console.ReadLine());
            y = int.Parse(Console.ReadLine());
            try
            {
                if (y % 2 > 0)
                {
                    //OddNumberException ONE = new OddNumberException();
                    //throw ONE;
                    throw new OddNumberException();
                }
                z = x / y;
                Console.WriteLine(z);
            }
            catch (OddNumberException one)
            {
                Console.WriteLine(one.Message);
            }

            Console.WriteLine("End of the program");
            Console.ReadKey();
        }
    }
}

OUTPUT:

Creating Custom Exception in C#

Why do we need to create custom exceptions in C#?

If none of the already existing .NET exception classes serve our purpose then we need to go for custom exceptions in C#.

For Example, I have an asp.net web application. The application should allow the user to have only one logged in session. If the user is already logged in, and if he opens another browser window and tries to log in again, the application should throw an error stating he is already logged in another browser window.

Within the .NET framework, we do not have any exception that adequately describes this problem. So this scenario is one of the examples where you want to create a custom exception.

We know that an exception is a class. So to create a Custom exception, Create a class that derives from System.Exception class. As a convention, end the class name with Exception suffix. All .NET exceptions end with, exception suffix. If you don’t do so, you won’t get a compiler error, but you will be deviating from the guidelines for creating custom exceptions.

public class UserAlreadyLoggedInException : Exception
{
}

Provide a public constructor that takes a string parameter. This constructor simply passes the string parameter, to the base exception class constructor.

public UserAlreadyLoggedInException(string message) : base(message)
{
}

Using InnerExceptions, you can also track back the original exception. If you want to provide this capability for your custom exception class, then overload the constructor as shown below.

public UserAlreadyLoggedInException(string message, Exception innerException)
    : base(message, innerException)
{
}

If you want your Exception class object to work across application domains, then the object must be serializable. To make your exception class serializable mark it with Serializable attribute and provide a constructor that invokes the base Exception class constructor that takes in SerializationInfo and StreamingContext objects as parameters.

[Serializable] 
public class UserAlreadyLoggedInException : Exception
{ 
    public UserAlreadyLoggedInException(SerializationInfo info, StreamingContext context): base(info, context)
    {
    }
}

Note: It is also possible to provide your own custom serialization, which will discuss in a later session.

Example2: Create a custom exception in C#:
using System;
using System.Runtime.Serialization;
namespace ExceptionHandlingDemo
{
    [Serializable]
    public class UserAlreadyLoggedInException : Exception
    {
        public UserAlreadyLoggedInException(string message)
            : base(message)
        {
        }

        public UserAlreadyLoggedInException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        public UserAlreadyLoggedInException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                throw new UserAlreadyLoggedInException("User Already logged in");
            }
            catch (UserAlreadyLoggedInException ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("End of the program");
            Console.ReadKey();
        }
    }
}

In the next article, I am going to discuss the Inner Exception in C# with examples. Here, in this article, I try to explain how to Create a Custom Exception in C# step by step with some examples. I hope now you understood the need and use of custom exceptions in C#.

1 thought on “Custom Exception in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *