Custom exceptions in C#.NET

In this article, I am going to discuss how to create a Custom Exception in C# with examples. At first we are going to see what is Exception.

What is an Exception?

Exceptions are a type of error that occurs during the execution of an application. Errors are typically problems that are not expected. Whereas, exceptions are expected to happen within the application’s code for various reasons.

Applications use exception handling logic to explicitly handle the exceptions when they happen.  Exceptions can occur for a wide variety of reasons. From the infamous NullReferenceException to a database query timeout.

The exceptions are anomalies that occur during the execution of a program.Exception handling is a mechanism in .NET framework to detect and handle run time errors. They can be because of user, logic or system errors. If a user (programmer) does not provide a mechanism to handle these anomalies, the .NET runtime environment provides a default mechanism, which terminates the program execution.

Exceptions allow an application to transfer control from one part of the code to another. When an exception is thrown, the current flow of the code is interrupted and handed back to a parent try catch block. C# exception handling is done with the follow keywords: try, catch, finally, and throw

  • try – A try block is used to encapsulate a region of code. If any code throws an exception within that try block, the exception will be handled by the corresponding catch.
  • catch – When an exception occurs, the Catch block of code is executed. This is where you are able to handle the exception, log it, or ignore it.
  • finally – The finally block allows you to execute certain code if an exception is thrown or not. For example, disposing of an object that must be disposed of.
  • throw – The throw keyword is used to actually create a new exception that is the bubbled up to a try catch finally block.
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:

namespace CustomExceptionHandling
{
    //Creating our own Exception Class by inheriting Exception class
    public class EvenNumberException : Exception
    {
        //Overriding the Message property
        public override string Message
        {
            get
            {
                return "Divisor cannot be Even number";
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int a, b, z;
            Console.WriteLine("ENTER TWO INTEGER NUMBERS:");
            a = int.Parse(Console.ReadLine());
            b = int.Parse(Console.ReadLine());
            try
            {
                if (b % 2 = 0)
                {
                    //EvenNumberException Even = new EvenNumberException();
                    //throw Even;
                    throw new EvenNumberException();
                }
                z = a / b;
                Console.WriteLine(z);
            }
            catch (EvenNumberException Even)
            {
                Console.WriteLine(Even.Message);
            }
            Console.WriteLine("End of the program");
            Console.ReadKey();
        }
    }
}

Define custom exception class:

[Serializable]
public class CustomException : Exception
{
    public CustomException()
        : base() { }
    
    public CustomException(string message)
        : base(message) { }
    
    public CustomException(string format, params object[] args)
        : base(string.Format(format, args)) { }
    
    public CustomException(string message, Exception innerException)
        : base(message, innerException) { }
    
    public CustomException(string format, Exception innerException, params object[] args)
        : base(string.Format(format, args), innerException) { }
    
    protected CustomException(SerializationInfo info, StreamingContext context)
        : base(info, context) { }
}

Example:

1. Throw exception with out message
Hide   Copy Code

throw new CustomException()

2. Throw exception with simple message
Hide   Copy Code

throw new CustomException(message)

3. Throw exception with message format and parameters
Hide   Copy Code

throw new CustomException("Exception with parameter value '{0}'", param)

4. Throw exception with simple message and inner exception
Hide   Copy Code

throw new CustomException(message, innerException)

5. Throw exception with message format and inner exception. Note that, the variable length params are always floating.
Hide   Copy Code

throw new CustomException("Exception with parameter value '{0}'", innerException, param)

6. The last flavor of custom exception constructor is used during exception serialization/deserialization.

0 0 vote
Article Rating

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x