Custom Exceptions
In this page:
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
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);
}
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: