Light Mode Image

C# Custom Exception

You can create custom exceptions by defining a new class that inherits from the System.Exception class or one of its derived classes.

 

Here's a simple example of creating a custom exception,

using System;

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

    public CustomException(string message) : base(message) { }

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

    // You can add additional properties or methods specific to your custom exception if needed
}

 

In the example above, CustomException is a custom exception class that inherits from the Exception class.

 

It provides three constructors that you can use to create instances of this exception with different levels of detail.

 

Now, you can throw this custom exception in your code like any other exception.

public class MyClass
{
    public void SomeMethod()
    {
        // Some code...

        // Throw the custom exception
        throw new CustomException("This is a custom exception message.");

        // More code...
    }
}

 

When an instance of CustomException is thrown, it can be caught using a catch block that specifically catches this type of exception.

 

try
{
    // Code that may throw the custom exception
    MyClass instance = new MyClass();
    instance.SomeMethod();
}
catch (CustomException ex)
{
    // Handle the custom exception
    Console.WriteLine($"Custom Exception: {ex.Message}");
}
catch (Exception ex)
{
    // Handle other exceptions
    Console.WriteLine($"General Exception: {ex.Message}");
}

 

This way, you can create and use custom exceptions in your C# code to provide more meaningful information about specific error conditions in your application.