Custom Exceptions
Learn how to use your own exception types with SGuard guards.
Overview
While SGuard provides sensible default exceptions for each guard method, you often need to throw domain-specific
exceptions. Every ThrowIf.* guard can throw yours instead.
Ways to Use Custom Exceptions
1. Pass a Factory (recommended)
Pass a lambda that creates the exception. It runs only when the guard fails, and the compiler checks the constructor call like any other code:
ThrowIf.NegativeOrZero(quantity, () => new DomainValidationException("Quantity must be greater than zero."));
ThrowIf.GreaterThan(amount, balance, () => new InsufficientFundsException(accountId, amount));
A lambda that doesn't capture variables, like the first one, is cached by the compiler, so a passing guard allocates
nothing. One that captures variables (accountId, amount) allocates a small closure per call, which is still far
cheaper than creating an exception.
Every guard has a factory overload. If the factory returns null, the guard throws InvalidOperationException.
When to use: whenever you throw your own exception. It is the only option that creates the exception lazily and lets it take arguments.
2. Pass a Custom Exception Instance
Provide a ready-made exception:
ThrowIf.LessThanOrEqual(quantity, 0, new DomainValidationException("Quantity must be greater than zero."));
The exception is an argument, so it is created on every call, even when the guard passes. Prefer a factory: add () =>
in front of new. The guards added in 3.0 take only factories.
3. Use Generic TException
Specify the exception type as a generic parameter and let SGuard create it with its parameterless constructor:
ThrowIf.Between<int, int, int, MyCustomException>(value, min, max);
ThrowIf.GreaterThan<int, int, MyCustomException>(quantity, maxQuantity);
These overloads require where TException : Exception, new(), so the exception type needs a public parameterless
constructor. The exception is created only when the guard fails.
When to use: the exception type alone says what went wrong, and you don't need a message.
Constructor arguments (obsolete)
Before 3.0, exceptions that needed constructor arguments were created from an object[]:
// Obsolete (SGUARD001)
ThrowIf.NullOrEmpty<string, ArgumentException>(value, ["Value is required", "customParamName"]);
// Instead
ThrowIf.NullOrEmpty(value, () => new ArgumentException("Value is required", "customParamName"));
These overloads match a constructor with reflection when the guard fails, so a wrong argument list surfaces only at run time, and trimming or Native AOT can remove the constructor. They still work and will be removed in 4.0; see Obsolete APIs.
Which Guards Support Which Variant
| Guard | Factory | Exception instance | TException : new() |
|---|---|---|---|
NullOrEmpty (value or span) | Yes | Yes (value) | No |
NullOrEmpty (with selector) | Yes | Yes | Yes |
GreaterThan, GreaterThanOrEqual, LessThanOrEqual | Yes | Yes | Yes |
LessThan | Yes | Yes | No |
Between | Yes | Yes | Yes |
Any, All | Yes | Yes | No |
Null, NullOrWhiteSpace, OutOfRange, Negative, NegativeOrZero, Zero, Equal, NotEqual, NotDefined, LongerThan, ShorterThan | Yes | No | No |
Built-in Exception Types
SGuard provides an exception type for each guard (namespace SGuard.Exceptions), used when no custom exception is
specified:
| Exception | Base type |
|---|---|
NullOrEmptyException, NullOrWhiteSpaceException, AnyException, AllException | ArgumentException |
NullException | ArgumentNullException |
LessThanException, LessThanOrEqualException, GreaterThanException, GreaterThanOrEqualException, BetweenException, OutOfRangeException, NegativeException, NegativeOrZeroException, ZeroException, EqualException, NotEqualException, NotDefinedException, LongerThanException, ShorterThanException | ArgumentOutOfRangeException |
They are all ArgumentExceptions, so catch (ArgumentException) handles every guard failure. ParamName holds the
argument expression from the call site, and the message names it too:
try
{
ThrowIf.GreaterThan(request.Age, limit);
}
catch (GreaterThanException ex)
{
// ex.ParamName == "request.Age"
// ex.Message == "Left value is greater than right value. Actual: left=request.Age, right=limit."
}
Including Values in Messages
By default the checked values are left out of built-in exception messages and Exception.Data, because messages
end up in logs and error trackers and values may be passwords, tokens or personal data. To include them, set this
once at startup:
SGuardOptions.IncludeValuesInExceptions = true;
// ThrowIf.GreaterThan(request.Age, 1000) with request.Age == 4217 now throws:
// "'4217' is greater than '1000'. Actual: left=request.Age, right=1000."
Each value is written with ToString() and truncated to 64 characters (SGuardOptions.MaxValueLength), and
Exception.Data holds those formatted strings. Enable it only when the checked values can't contain secrets or
personal data. The option affects only the built-in exceptions, not exceptions you supply.
Exception Requirements
What your exception type needs depends on the overload you use:
- Factory or exception instance: nothing; you construct it yourself.
TExceptionwithnew(): a public parameterless constructor (enforced at compile time).
Following the standard .NET exception constructors keeps every option open:
public class MyException : Exception
{
public MyException() { }
public MyException(string message) : base(message) { }
public MyException(string message, Exception innerException) : base(message, innerException) { }
}
Real-World Examples
Domain Validation Exception
public class OrderValidationException(string message) : Exception(message);
ThrowIf.NegativeOrZero(order.Quantity, () => new OrderValidationException("Order quantity must be positive."));
Business Rule Exception
public class InsufficientStockException(string message, string sku) : InvalidOperationException(message)
{
public string Sku { get; } = sku;
}
ThrowIf.GreaterThan(item.Quantity, stock,
() => new InsufficientStockException($"Insufficient stock for SKU '{item.Sku}'.", item.Sku));
Validation Exception with Context
public class UserValidationException(string message, string paramName, string tenantId)
: ArgumentException(message, paramName)
{
public string TenantId { get; } = tenantId;
}
var name = ThrowIf.NullOrWhiteSpace(username,
() => new UserValidationException("Username is required", nameof(username), tenantId));
Combining with Callbacks
Custom exceptions work with callbacks. The callback receives Failure before the factory runs:
ThrowIf.LessThan(value, threshold,
() => new BusinessRuleException("Value below threshold"),
SGuardCallbacks.OnFailure(() => logger.LogError("Business rule violated")));
Best Practices
- Pass a factory, not an instance: the exception is created only when it is needed
- Use meaningful exception types: create domain-specific exceptions that clearly communicate what went wrong
- Include context: add properties to your exceptions that help with debugging and error handling
- Don't over-engineer: often the built-in exception, or
ArgumentException, is enough
Next Steps
- Real-World Examples - See custom exceptions in action
- API Reference - Complete ThrowIf API
- Upgrading to 3.0 - Moving from constructor arguments to factories