-
Notifications
You must be signed in to change notification settings - Fork 0
Handling Exceptions With Try
Sometimes you need to call code that might throw an exception — for example, parsing text, reading a file, or calling an external library. Resultron gives you Try and TryAsync to catch these exceptions automatically and turn them into a Result.
You could write this manually:
Result<int> result;
try
{
var value = int.Parse(input);
result = Result<int>.Success(value);
}
catch (Exception ex)
{
result = Result<int>.Failure(new Error(ex.GetType().Name, ex.Message));
}This works, but it is repetitive. Try does this exact pattern for you in one line:
Result<int> result = Result<int>.Try(() => int.Parse(input));Use this when the action does not return anything:
Result result = Result.Try(() =>
{
File.Delete("temp.txt");
});
result.Match(
onSuccess: () => Console.WriteLine("File deleted."),
onFailure: error => Console.WriteLine($"Could not delete file: {error.Description}")
);Use this when the action returns a value:
Result<int> result = Result<int>.Try(() => int.Parse("abc"));
result.Match(
onSuccess: value => Console.WriteLine($"Parsed: {value}"),
onFailure: error => Console.WriteLine($"Could not parse: {error.Description}")
);
// Output: Could not parse: The input string 'abc' was not in a correct format.When an exception is caught, Resultron builds the Error like this:
new Error(Code: ex.GetType().Name, Description: ex.Message)-
Codebecomes the exception's class name, for example"FormatException","IOException", or"NullReferenceException". -
Descriptionbecomes the exception's message text.
This means you get a structured error even from unexpected exceptions, without writing any extra code.
Both Try methods check that you actually passed in an action:
ArgumentNullException.ThrowIfNull(action);If you pass null instead of a real function, Resultron throws an ArgumentNullException immediately. This is different from a normal "failure" — it means your code has a bug (calling Try with nothing to run), so it fails loudly instead of quietly returning a failed Result.
Try is great for turning expected, recoverable problems (like bad user input) into a Result. For truly exceptional situations that your program cannot recover from (like running out of memory, or a critical startup failure), a normal try/catch (or letting the exception crash the app) may still be the right choice.
Next: Async Operations shows how to use TryAsync in real async code.