Custom exceptions
Context: Custom exceptions allow you to define application-specific error types. They should inherit from Exception (or a derived class) and follow standard conventions: provide constructors that call the base constructors, implement serialization for cross‑domain scenarios, and add custom properties when needed. Custom exceptions make error handling more expressive and maintainable.
Usage Example
Section titled “Usage Example”using System;
public class InsufficientFundsException : Exception{ public decimal Amount { get; } public decimal Balance { get; }
public InsufficientFundsException() { }
public InsufficientFundsException(string message) : base(message) { }
public InsufficientFundsException(string message, Exception inner) : base(message, inner) { }
public InsufficientFundsException(decimal amount, decimal balance) : base($"Insufficient funds: requested {amount:C}, balance {balance:C}") { Amount = amount; Balance = balance; }}
class BankAccount{ public decimal Balance { get; private set; }
public void Withdraw(decimal amount) { if (amount > Balance) throw new InsufficientFundsException(amount, Balance); Balance -= amount; }}
class Program{ static void Main() { var account = new BankAccount(); try { account.Withdraw(100); } catch (InsufficientFundsException ex) { Console.WriteLine(ex.Message); } }}Output console
Section titled “Output console”dotnet runInsufficient funds: requested $100.00, balance $0.00Important notes
Section titled “Important notes”- Avoid inheriting from
ApplicationException(it is no longer recommended). - Provide at least the three standard constructors.
- Mark the exception as
[Serializable]if you need cross‑AppDomain or cross‑process support.
Real-world usage example
Section titled “Real-world usage example”Validation framework – Create ValidationException with a collection of validation errors.
See .NET docs on creating custom exceptions.