C# Custom Exception

In C#, custom exceptions are exceptions that you define yourself to handle specific error conditions in your application. These exceptions inherit from the built-in Exception class, allowing you to add any custom behavior or data relevant to your application’s error-handling needs.

How to Create Custom Exception

1. Inherit from the Exception class.

2. Optionally, add constructors to pass error messages or inner exceptions.

Create Custom Exception Class

we are creating a custom exception called InvalidAgeException that will be thrown when an invalid age is provided (like a negative number).

Example 1: create custom exception class


using System;

public class InvalidAgeException : Exception
{
    // Default constructor
    public InvalidAgeException() { }

    // Constructor with a message
    public InvalidAgeException(string message) : base(message) { }

    // Constructor with message and inner exception
    public InvalidAgeException(string message, Exception innerException)
        : base(message, innerException) { }
}

2. Throwing and Catching the Custom Exception

Now, we’ll write a method that throws this custom exception if the provided age is invalid. In the Main method, we’ll catch and handle this exception.


class MyProgram
{
    static void Main()
    {
        try
        {
            ValidateAge(-21);  // Invalid age
        }
        catch (InvalidAgeException ex)
        {
            Console.WriteLine($"Caught exception: {ex.Message}");
        }
    }

    static void ValidateAge(int age)
    {
        if (age < 0)
        {
            throw new InvalidAgeException("Age cannot be negative");
        }

        Console.WriteLine($"Age set to: {age}");
    }
}

Complete Program of Custom Exception


using System;

public class InvalidAgeException : Exception
{
    // Default constructor
    public InvalidAgeException() { }

    // Constructor with a message
    public InvalidAgeException(string message) : base(message) { }

    // Constructor with message and inner exception
    public InvalidAgeException(string message, Exception innerException)
        : base(message, innerException) { }
}

class MyProgram
{
    static void Main()
    {
        try
        {
            ValidateAge(-21);  // Invalid age
        }
        catch (InvalidAgeException ex)
        {
            Console.WriteLine($"Caught exception: {ex.Message}");
        }
    }

    static void ValidateAge(int age)
    {
        if (age < 0)
        {
            throw new InvalidAgeException("Age cannot be negative");
        }

        Console.WriteLine($"Age set to: {age}");
    }
}

Output:

Name: John, Age: 35