LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 3912 min read

Custom Exceptions

Learn how to define your own exception types by inheriting from the Exception class.

Why Custom Exceptions?

Built-in exceptions like `ArgumentException` are general-purpose. A custom exception type lets you represent domain-specific failures clearly, and lets calling code catch exactly the failure it cares about.

Creating a Custom Exception

class InsufficientFundsException : Exception
{
public decimal Shortfall { get; }
public InsufficientFundsException(decimal shortfall)
: base($"Insufficient funds. Short by {shortfall:C}.")
{
Shortfall = shortfall;
}
}

Throwing and Catching It

class Account
{
public decimal Balance = 100;
public void Withdraw(decimal amount)
{
if (amount > Balance)
throw new InsufficientFundsException(amount - Balance);
Balance -= amount;
}
}
var account = new Account();
try
{
account.Withdraw(150);
}
catch (InsufficientFundsException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine($"Shortfall: {ex.Shortfall:C}");
}
Output

Click Run to see what this code prints.

FAQs

No — reserve custom exceptions for meaningful, domain-specific failures your calling code will actually want to handle differently. Overusing them adds noise.

Summary

  • Custom exceptions inherit from Exception (or a more specific built-in type).
  • They can carry extra data relevant to the failure.
  • Use them for meaningful, domain-specific error conditions.
Next Lesson →

Namespaces