Back to results for “Exception Handling”
C# › Exception Handling

When should you create custom exceptions vs use built-in ones?

Advanced

Answer

Create a custom exception when callers need to catch a domain-specific condition distinctly; otherwise reuse built-ins (ArgumentException, InvalidOperationException). Keep a meaningful hierarchy.
public class InsufficientFundsException(decimal shortfall) : Exception;
Real-world example A banking layer throws InsufficientFundsException so the API can map it to a 422 response.