C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Custom Exceptions

C# Custom Exceptions

Create your own exception classes to represent domain-specific error conditions clearly.

1 - Creating a Custom Exception

public class InsufficientFundsException : Exception
{
    public decimal Amount    { get; }
    public decimal Balance   { get; }

    public InsufficientFundsException(decimal amount, decimal balance)
        : base($"Cannot withdraw {amount:C}. Balance is {balance:C}.")
    {
        Amount  = amount;
        Balance = balance;
    }
}

public class BankAccount
{
    private decimal _balance;

    public BankAccount(decimal initial) => _balance = initial;

    public void Withdraw(decimal amount)
    {
        if (amount > _balance)
            throw new InsufficientFundsException(amount, _balance);
        _balance -= amount;
    }
}

var account = new BankAccount(100m);
try
{
    account.Withdraw(200m);
}
catch (InsufficientFundsException ex)
{
    Console.WriteLine(ex.Message);
    Console.WriteLine($"Tried: {ex.Amount:C}, Had: {ex.Balance:C}");
}

2 - Exception Hierarchy

// Good practice: create a base exception for your domain
public class AppException : Exception
{
    public AppException(string message) : base(message) { }
    public AppException(string message, Exception inner) : base(message, inner) { }
}

public class ValidationException : AppException
{
    public string Field { get; }
    public ValidationException(string field, string message)
        : base(message) => Field = field;
}

Note: Name custom exceptions ending in Exception (e.g. InsufficientFundsException). Always provide at least two constructors — one with just a message and one that also accepts an inner exception, to support exception chaining.

-Tip-

C# {"id":43,"topic_id":3,"name":"C# Exception Handling","slug":"c-exception-handling","image":null,"description":"<p>Handle errors gracefully with try\/catch\/finally, custom exceptions, and filters.<\/p>","icon":null,"class":null,"color":null,"status":0,"order":12,"created_at":"2026-05-03T02:03:02.000000Z","updated_at":"2026-05-03T02:03:02.000000Z"} - List of Contents

Related Tutorials: