c sharp

How to Create Custom Exceptions in C#

Errors and exceptions are some of the most common things that we share as developers. Whether working with a new and experimental language or a seasoned language that has existed for years, you are bound to deal with it.

Although each language and package comes with a pre-defined list of exceptions and how to handle them, we come across instances where we need to define custom exceptions and their handling mechanisms. This is useful when we need precise error messages and graceful error handling.

In this tutorial, we will learn how to use the C# features to define the custom exceptions and handling.

What Is an Exception?

An exception in an application that refers to an unexpected event that occurs during the execution of the program. For example, at runtime, an event can occur that can alter the flow of the program. If not handled, the exceptions can cause the program to abort.

Custom exceptions are user-defined exceptions that are derived from the “Exception” class or one of the standard-derived classes.

Create a Custom Exception

In C#, we can create a custom exception by defining a class that is derived from the “System.Exception” class.

Take a look at the following example implementation:

public class CustomException : Exception
{
    public CustomException() : base()
    {
    }

    public CustomException(string message) : base(message)
    {
    }
    public CustomException(string message, Exception inner) : base(message, inner)
    {
    }
}

The given example shows a basic template to define a custom exception using the C# “Exception” class.

We start by creating a new class called “CustomException” which is derived from the base “Exception” class.

In the class, we create three constructors, each calling the base class constructor with a different parameter. This ensures that our custom exception works like any built-in exception.

Use a Custom Exception

We can use the “throw” keyword once we define our custom exception to run the exception. An example demonstration is shown in the following:

using System;
using System.Runtime.InteropServices;
public class CustomException : Exception
{
    public CustomException() : base()
    {
    }
    public CustomException(string message) : base(message)
    {
    }
    public CustomException(string message, Exception inner) : base(message, inner)
    {
    }
}
class Program
{
    static void Main()
    {
        int number = -10;
        if (number < 0)
        {
            throw new CustomException("Err!, Use of Negative Numbers.");
        }
        Console.WriteLine("Number is " + number);
    }
    }

In the given example, we use the “throw” keyword to call the “CustomException” with an error message if the provided value is a negative number.

Output:

Unhandled exception. CustomException: Err!, Use of Negative Numbers.

Handle a Custom Exception

Like all exceptions, we need to handle them gracefully using the try-catch blocks. Luckily, there is no difference in how we handle the custom exceptions and how we handle the built-in exceptions.

Consider the following example demonstration:

using System;
using System.Runtime.InteropServices;
public class CustomException : Exception
{
    public CustomException() : base()
    {
    }

    public CustomException(string message) : base(message)
    {
    }
    public CustomException(string message, Exception inner) : base(message, inner)
    {
    }
}
class Program
{
    static void Main()
    {
        int number = -10;
        try
        {
            if (number < 0)
            {
                throw new CustomException("Opps, negative number!");
            }
        }
        catch (CustomException ex)
        {
            Console.WriteLine(ex.Message);
        }

    }
    }

In this case, we gracefully handle the error and return a custom message when an error occurs.

Conclusion

This tutorial taught us how to define and use the custom error messages when working within a C# application.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list