Let’s go through custom exceptions in C# β€” useful when you want to define your own error types for specific situations.


πŸ“Œ 1. What Are Custom Exceptions?

  • A custom exception is a class you create that inherits from System.Exception (or one of its derived classes).

  • Allows you to signal application-specific errors

  • Can include extra properties or methods for more information


πŸ“Œ 2. Why Use Custom Exceptions?

  1. Improve readability of error handling

  2. Provide more context than standard exceptions

  3. Allow specific catch blocks for particular errors

  4. Encapsulate domain-specific validation


πŸ“Œ 3. Creating a Custom Exception

Syntax

public class NegativeAgeException : Exception
{
    // Default constructor
    public NegativeAgeException() { }
 
    // Constructor with message
    public NegativeAgeException(string message) : base(message) { }
 
    // Constructor with message and inner exception
    public NegativeAgeException(string message, Exception inner) : base(message, inner) { }
}
  • Always inherit from Exception (or ApplicationException in older code)

  • Provide constructors to allow message passing


πŸ“Œ 4. Using a Custom Exception

void ValidateAge(int age)
{
    if (age < 0)
        throw new NegativeAgeException("Age cannot be negative!");
}
 
try
{
    ValidateAge(-5);
}
catch (NegativeAgeException ex)
{
    Console.WriteLine("Caught custom exception: " + ex.Message);
}

Output:

Caught custom exception: Age cannot be negative!

πŸ“Œ 5. Custom Exception with Extra Properties

public class InvalidTransactionException : Exception
{
    public decimal Amount { get; }
 
    public InvalidTransactionException(string message, decimal amount) : base(message)
    {
        Amount = amount;
    }
}
 
// Usage
try
{
    throw new InvalidTransactionException("Transaction amount too high", 5000);
}
catch (InvalidTransactionException ex)
{
    Console.WriteLine($"{ex.Message} - Amount: {ex.Amount}");
}

Output:

Transaction amount too high - Amount: 5000
  • Can store extra information related to the exception

πŸ“Œ 6. Best Practices

  1. Name exception classes ending with Exception

  2. Inherit from Exception (or ApplicationException)

  3. Include constructors with message and inner exception

  4. Only throw custom exceptions when standard ones are not descriptive enough


πŸ“Œ 7. Summary Table

FeatureDescription
Base ClassException (or ApplicationException)
ConstructorsDefault, message, message + inner exception
Extra PropertiesOptional; store additional info
UsageThrow with throw new CustomException(...)
Catchingcatch (CustomException ex)

βœ… Tip:

  • Use custom exceptions to make your code self-documenting

  • Combine with try-catch-finally for robust error handling