Custom Exceptions
Prerequisites: Exception handling
class InsufficientFundsException : Exception {
public InsufficientFundsException(string message) : base(message) {}
}
class BankAccount {
private double _balance;
public void Withdraw(double amount) {
if (amount > _balance) {
throw new InsufficientFundsException(
$"Cannot withdraw {amount}; balance is {_balance}"
);
}
_balance -= amount;
}
}
Exactly the same reasoning as Java's version of this lesson: a named, specific exception type lets calling code react to that particular failure differently from any other.