How do custom exception classes work in C#, and what's the recommended convention for creating one?
Short answer
A custom exception should inherit from Exception (or a more specific built-in exception type), be named ending in 'Exception', and typically provide the standard set of constructors (parameterless, message-only, message+innerException) to remain compatible with standard…
Advertisement
AModel answer
A custom exception should inherit from Exception (or a more specific built-in exception type), be named ending in 'Exception', and typically provide the standard set of constructors (parameterless, message-only, message+innerException) to remain compatible with standard exception-handling conventions and serialization.
public class InsufficientFundsException : Exception {
public decimal ShortfallAmount { get; }
public InsufficientFundsException(decimal shortfall)
: base($"Insufficient funds. Short by {shortfall:C}.") {
ShortfallAmount = shortfall;
}
}Real-world example
Throwing a domain-specific exception (like InsufficientFundsException) that carries meaningful business context beyond a generic message string.
Likely follow-ups
- Why is it considered good practice to include the standard set of base constructors on a custom exception?
Related topics