C#
Beginner
1 min read
Custom Exceptions
Example
// Custom exception hierarchy
// Base domain exception
public class DomainException : Exception
{
public string DomainContext { get; }
public DomainException(string message, string context)
: base(message)
{
DomainContext = context;
}
public DomainException(string message, string context, Exception inner)
: base(message, inner)
{
DomainContext = context;
}
}
// Specific subclass with extra data
public class ValidationException : DomainException
{
public string FieldName { get; }
public object? AttemptedValue { get; }
public ValidationException(string field, object? value, string message)
: base(message, context: "Validation")
{
FieldName = field;
AttemptedValue = value;
}
public override string ToString() =>
$"[ValidationException] Field={FieldName}, Value={AttemptedValue}, Message={Message}";
}
// Usage
static void SetAge(int age)
{
if (age < 0 || age > 150)
throw new ValidationException(nameof(age), age, "Age must be between 0 and 150.");
}
try
{
SetAge(-5);
}
catch (ValidationException ex)
{
Console.WriteLine(ex);
Console.WriteLine($"Context: {ex.DomainContext}");
}
catch (DomainException ex)
{
Console.WriteLine($"Domain error [{ex.DomainContext}]: {ex.Message}");
}