← Back to C# Course | Chapter 10: Exception Handling | Lesson 3 of 6

Custom Exceptions

In this page:

  1. Custom Exceptions

Custom Exceptions

You can define your own exception type by inheriting from Exception (or a more specific subclass), which lets calling code catch a precise, meaningful error type for your domain. Custom exceptions usually forward a message to the base constructor. This is standard practice for libraries reporting domain-specific failures.

Note: Name custom exceptions ending in "Exception", like InsufficientFundsException.

Example: Custom Exceptions

markup
using System;

class InsufficientFundsException : Exception
{
    public InsufficientFundsException(string message) : base(message) { }
}

class Account
{
    public decimal Balance = 100;

    public void Withdraw(decimal amount)
    {
        if (amount > Balance)
            throw new InsufficientFundsException("Not enough funds");
        Balance -= amount;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Account acc = new Account();
        try
        {
            acc.Withdraw(500);
        }
        catch (InsufficientFundsException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.