C# Custom Exception

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

 

While creating our own user-defined exception class, we need to make sure that the end of class name will contain “Exception” word and it must be derived from Exception base class. After creating our own custom exception class, we need to implement the three common constructors like 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 exceptions 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 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 like as shown below.

 

Name is Empty

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

 
 

NEXT

C# Var Keyword  
 

Topics Covered