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

Custom Exceptions

A custom exception is an alarm you design yourself for your own special kind of problem. It makes error messages meaningful for your program.

In this page:

  1. Custom Exceptions
Syntax
csharp
class CustomException : Exception
{
    public CustomException(string message) : base(message) { }
}

throw new CustomException("message");

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);
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Not ending the class name with Exception, which breaks the .NET naming convention.
  2. Forgetting to call the base constructor with the message, so the message is lost.
  3. Deriving from ApplicationException instead of Exception, which is not recommended.
🔒

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.