In C#  we can create user-defined or custom exception as per our needs. It is used to make the meaningful exception. To do this, we need to inherit Exception class, if you are new to exception handling in C#, read Exception handling in C# (With try-catch-finally block details) first ,as we will be using it's concept in this article to create custom exception in C#.

.NET provides lots of exception classes, which are all derived from the base class Exception.

Here are the Exception classes

  • SystemException- Serves as the base class for system exceptions namespace.
  • ArithmeticException- The exception that is thrown for errors in an arithmetic, casting, or conversion operation.
  • DivideByZeroException- The exception that is thrown when there is an attempt to divide an integral or Decimal value by zero.
  • FormatException- The exception that is thrown when the format of an argument is invalid, or when a composite format string is not well formed.
  • IndexOutOfRangeException- This exception means an array index is out of bounds.
  • NotSupportedException- This exception indicates that a method is not implemented by a class.
  • NullReferenceException- This exception means attempt to use an unassigned reference.
  • OutOfMemoryException- This exception means not enough memory to continue execution.
  • StackOverflowException- The exception that is thrown when the execution stack overflows because it contains too many nested method calls.

However, if none of the pre-defined exceptions meets your needs, you can create your own exception classes by deriving from the Exception class.

When creating your own exceptions, it is always good to end the class name of the user-defined exception with the word "Exception", and implement the three common constructors, as shown in the following example.

This example defines a new exception class named StudentListNotFoundException. The class is derived from Exception and includes three constructors.

using System;

//inherit Exception class, to create Custom Exception class
public class StudentListNotFoundException: Exception
{
     //Class Constructor
    public StudentListNotFoundException()
    {
    }
    
    //class constructor with parameter as Error message
    public StudentListNotFoundException(string message)
        : base(message)
    {
    }

   // constructor with Exception details as parameter
    public StudentListNotFoundException(string message, Exception inner)
        : base(message, inner)
    {
    }
}

Usually, a C# programmer can define Custom Exception considering following points:

  • Derive a Custom Exception Class from Exception class
  • Define all three constructors as explained above

Now as you have got the basic of creating your own custom exception in C#, let create a complete example using Console application.

Create a new project in your Visual Studio, by navigating to File->New->Project-> Select "Console Applicaiton" -> Enter the name "CustomExceptionHandling" -> Click "Ok"

In your program.cs use the below C# code

using System;

namespace CustomExceptionHandling
{
   //Custom User defiened Exception Created here, using Exception as base class
    public class TestCustomException : Exception
    {
       
        public TestCustomException(string message) : base(message)
        {
            this.HelpLink = "Visit to qawithexperts.com for more information";
            this.Source = "This is source of Error";
        }
       
    }
    
	//Usual Class with method Show(), which throws Exception with message
    public class MyClass
    {
        public static void Show()
        {
            throw new TestCustomException("This is Custom Exception example in C#");
        }
    }
	
    public class Program
    {
        public static void Main(string[] args)
        {
			//enclose method inside try
            try
            {
                MyClass.Show();
            }
			//catch User defined Exception
            catch (TestCustomException ex)
            {
                //Show Custom defined Error messages
                Console.WriteLine("Error Message:-" + ex.Message);
                Console.WriteLine("Hyper Link :-" + ex.HelpLink);
                Console.WriteLine("Source :- " + ex.Source);
               
            }
        }
    }
}

In the above C# code we have created a Custom Exception "TestCustomException" which is derived from "Exception" class, by calling MyClass.Show() method, we are throwing the "TestCustomException" exception.

Here is the output:

Error Message:-This is Custom Exception example in C#
Hyper Link :-Visit to qawithexperts.com for more information
Source :- This is source of Error

c-sharp-custom-exception-handling-min.png

You can use the fiddle here

For best practices, you should always create an app which handles exceptions and errors to prevent app crashes. So, always use try/catch/finally blocks around code that can potentially generate an exception.

In catch blocks, always order exceptions from the most specific to the least specific and use a finally block to clean up resources, whether you can recover or not.

When do we need Custom Exceptions, when there are already lots of Exception defined in .NET?

Sometimes, while creating an app, you may need to define exceptions on your own, instead of using .NET defined expcetions for better user experience.

For example, when a called is made to web-api from front-end to save data in database, but exception occurs do to not so correct values by user or your database table doesn't accept new values, you can show a useful message to user with your custom defined exception and message.

You may also like to read:

Extension Methods in C# (Explanation With Example)

Understanding C# Classes and Objects with example

How to convert string to int in C#?

how to convert UTC time to Local using C#?

Read file in C# (Text file .NET and .NET Core example)

Generate Class from XSD in C# (Using CMD or Visual Studio)

There is already an open datareader associated - error in C#

How can I run raw SQL query in C#? ( With and Without ADO.NET)

How to remove double quotes from string using C#?

How to find and extract only number from string in C#?

How to convert byte[] array to string and Vice versa in C#?