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?
-
Improve readability of error handling
-
Provide more context than standard exceptions
-
Allow specific catch blocks for particular errors
-
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
(orApplicationException
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
-
Name exception classes ending with
Exception
-
Inherit from
Exception
(orApplicationException
) -
Include constructors with message and inner exception
-
Only throw custom exceptions when standard ones are not descriptive enough
π 7. Summary Table
Feature | Description |
---|---|
Base Class | Exception (or ApplicationException ) |
Constructors | Default, message, message + inner exception |
Extra Properties | Optional; store additional info |
Usage | Throw with throw new CustomException(...) |
Catching | catch (CustomException ex) |
β Tip:
-
Use custom exceptions to make your code self-documenting
-
Combine with try-catch-finally for robust error handling