Skip to content

Handling Exceptions With Try

ferdi kurnaz edited this page Aug 27, 2026 · 1 revision

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.

Why not just use try/catch?

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));

Result.Try (no return value)

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}")
);

Result<T>.Try (with a return value)

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.

What goes into the Error?

When an exception is caught, Resultron builds the Error like this:

new Error(Code: ex.GetType().Name, Description: ex.Message)
  • Code becomes the exception's class name, for example "FormatException", "IOException", or "NullReferenceException".
  • Description becomes the exception's message text.

This means you get a structured error even from unexpected exceptions, without writing any extra code.

A note on null checks

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.

When should you still use a real try/catch?

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.

Clone this wiki locally