C# Custom Exception

As we learned in previous sections, c# has provided many built-in exception classes to handle runtime or unexpected errors in the application. In case if none of the predefined exception classes meet your needs, then you can create your own exception classes by deriving from Exception base class.

 

While creating your own user-defined exception class, you need to ensure that the end of class name contains the “Exception” word, and it must be derived from Exception base class. After creating your own custom exception class, you need to implement the three common constructors, as shown in the following example.

C# Create Custom Exception Class

Following is the example of creating a new exception class named “TutlaneCustomException” by deriving from Exception base class and including three constructors.

 

public class TutlaneCustomException: Exception
{
public TutlaneCustomException()
{
}
public TutlaneCustomException(string message): base(message)
{
}
public TutlaneCustomException(string message, Exception innerexception): base(message, innerexception)
{
}
}

By using throw keyword, we can raise an exception using TutlaneCustomException class in our program based on our requirements.

C# Custom Exception Example

Following is the example of creating a custom exception class (TutlaneCustomException) and throwing exceptions using a custom exception class in c#.

 

using System;

namespace TutlaneExamples
{
    class Program
    {
       static void Main(string[] args)
       {
          string name = null;
          if (string.IsNullOrEmpty(name))
          {
             throw new TutlaneCustomException("Name is Empty");
          }
          else
          {
             Console.WriteLine("Name: " + name);
          }
          Console.ReadLine();
       }
    }
    public class TutlaneCustomException: Exception
    {
       public TutlaneCustomException()
       {
       }
       public TutlaneCustomException(string message) : base(message)
       {
       }
       public TutlaneCustomException(string message, Exception innerexception) : base(message, innerexception)
       {
       }
    }
}

If you observe the above example, we created a custom exception class TutlaneCustomException by deriving from Exception base class, and we used a throw keyword to raise an exception.

 

When we execute the above example, we will get the result below.

 

Name is Empty

This is how you can create your own custom exception classes by deriving from Exception base class in c# based on our requirements.