-
Notifications
You must be signed in to change notification settings - Fork 0
Error Handling
Ahmad Al-freihat edited this page Jan 1, 2026
·
1 revision
NonEmptyList<T> maintains its non-empty invariant by throwing appropriate exceptions when violations are attempted.
Attempting to create from an empty collection throws ArgumentException:
// From empty array
NonEmptyList<int>.From(Array.Empty<int>());
// Throws: ArgumentException
// From empty list
NonEmptyList<int>.From(new List<int>());
// Throws: ArgumentExceptionSafe Alternative: Use TryFrom to handle potentially empty sources:
if (NonEmptyList<int>.TryFrom(source, out NonEmptyList<int>? result))
{
// Use result
}
else
{
// Handle empty case
}Calling Clear() throws NotSupportedException:
NonEmptyList<int> list = new(1, 2, 3);
list.Clear();
// Throws: NotSupportedExceptionAttempting to remove the last element throws InvalidOperationException:
NonEmptyList<int> single = new(1);
single.Remove(1);
// Throws: InvalidOperationException
single.RemoveAt(0);
// Throws: InvalidOperationExceptionRemoveRange throws if it would empty the list:
NonEmptyList<int> list = new(1, 2, 3);
list.RemoveRange(0, 3); // Remove all
// Throws: InvalidOperationExceptionFor reference types, adding null throws ArgumentNullException:
NonEmptyList<string> strings = new("a", "b");
strings.Add(null!);
// Throws: ArgumentNullException| Operation | Exception | Condition |
|---|---|---|
From(empty) |
ArgumentException |
Source is empty |
new(null) |
ArgumentNullException |
Null element (reference types) |
Clear() |
NotSupportedException |
Always |
Remove(last) |
InvalidOperationException |
Would empty the list |
RemoveAt(last) |
InvalidOperationException |
Would empty the list |
RemoveRange(all) |
InvalidOperationException |
Would empty the list |
Add(null) |
ArgumentNullException |
Null element (reference types) |
Validate(fail) |
ArgumentException |
Validation predicate fails |
-
Use
TryFromfor unknown sources:if (NonEmptyList<T>.TryFrom(source, out var result)) { // Safe to use result }
-
Check before remove operations:
if (list.Count > 1) { list.RemoveAt(0); }
-
Use
TryValidatefor user input:if (!list.TryValidate(predicate, out var failing)) { // Handle validation failure }
- Learn about Thread Safety for concurrent scenarios
- Explore ImmutableNonEmptyList for safer concurrent access