Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 1 · Lesson 7 · 6 min read

C# Exceptions vs Result Types

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: Guard Clauses, a Result Type and Safe Handling
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Use try, catch, finally and using correctly, decide between throwing an exception and returning a result, apply guard clauses to reject bad input early, and explain why raw exception details must never reach an API client.

Concept Explanation

C# exceptions work like JavaScript's, with more structure. You throw an object derived from Exception, catch it by type, and a finally block runs whether or not an error occurred. Catch clauses are matched in order and can carry a when filter that adds a condition without losing the original stack trace. The using statement, which you will see everywhere, guarantees that a disposable resource such as a file, a database connection, or an HTTP response is released when scope ends, even if an exception flies past. It is the tool for making sure a failure does not leak connections until the server runs out of them.

The harder skill is deciding when to throw. Exceptions are for situations the current code cannot reasonably handle and that indicate something exceptional, such as a corrupted file, an unavailable database, or a programming error. They are not for ordinary expected outcomes. A user typing letters into a number field is normal, and throwing an exception for it is both slow, since exceptions cost microseconds each rather than nanoseconds, and misleading. For expected failures, return a value that says so: the TryParse pattern returns a bool and an out parameter, and many teams also define a small Result type that carries either a value or an error code.

Guard clauses make the code that follows simpler and safer. Instead of nesting the main logic inside if statements, you check preconditions at the top and return or throw immediately. Modern C# provides helpers such as ArgumentNullException.ThrowIfNull and ArgumentOutOfRangeException.ThrowIfNegative that make these one-liners. Validating at the boundary of every public method means invalid state never travels deep into the system, where it would be far harder to diagnose. This is the same input discipline described on Day 1, applied inside the code instead of at the network edge.

Two habits matter for security and diagnosability. First, never swallow exceptions with an empty catch block: it hides bugs and lets the program continue in an undefined state. Catch only what you can actually handle and let the rest propagate to a central handler. Second, rethrow with a bare throw statement, which preserves the original stack trace, rather than throw ex, which resets it. And at the edge of your API, translate exceptions into a generic, safe error response and log the details privately. A stack trace, a SQL fragment, or a file path in an HTTP response is a gift to an attacker, because it reveals your framework versions, table names, and code structure.

SituationPreferred toolWhy
Bad user inputReturn a validation resultIt is an expected outcome, not an exception
Parsing text to a numberint.TryParseNo exception cost, no control flow by exception
Missing required argumentGuard clause that throwsIt is a programming error by the caller
File or network failureCatch specific exception, log, translateOutside your control, needs handling at a boundary
Releasing resourcesusing statementRuns even when an exception occurs
Reporting an error to an API clientGeneric problem responseNever expose stack traces or internals

Worked Example: Guard Clauses, a Result Type and Safe Handling

This example parses a quantity from text and returns a Result instead of throwing. It then shows a repository method that guards its inputs, releases a resource with using, catches only what it can handle, and preserves the stack trace when it must rethrow.

C#
public sealed record Error(string Code, string Message);

public sealed class Result<T>
{
    public T? Value { get; }
    public Error? Error { get; }
    public bool IsSuccess => Error is null;

    private Result(T? value, Error? error) { Value = value; Error = error; }
    public static Result<T> Ok(T value) => new(value, null);
    public static Result<T> Fail(string code, string message) => new(default, new Error(code, message));
}

public static class Quantity
{
    public static Result<int> Parse(string? raw)
    {
        if (!int.TryParse(raw, out var n))
            return Result<int>.Fail("quantity.invalid", "Quantity must be a whole number.");
        if (n is < 1 or > 100)
            return Result<int>.Fail("quantity.range", "Quantity must be between 1 and 100.");
        return Result<int>.Ok(n);
    }
}

public sealed class ImportService(ILogger<ImportService> logger)
{
    public async Task<int> CountLinesAsync(string path, CancellationToken ct)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(path);   // guard clause

        try
        {
            using var reader = new StreamReader(path);      // disposed even if we throw
            var count = 0;
            while (await reader.ReadLineAsync(ct) is not null) count++;
            return count;
        }
        catch (FileNotFoundException)
        {
            return 0;                                       // expected here, handled
        }
        catch (IOException ex)
        {
            logger.LogError(ex, "Failed reading import file");  // details go to the log
            throw;                                          // bare throw keeps the stack trace
        }
        // No empty catch, and no catch (Exception) that hides real bugs.
    }
}

Compare the two error paths. A bad quantity is an ordinary outcome returned as data, so the caller decides what message to show. A disk failure is exceptional, so it is logged in full for developers and rethrown so a central handler can convert it to a generic 500 response. Day 16 builds that handler.

Invalid input is an expected outcome returned as a Result and shown as a 400. Real failures throw and are caught by one global handler that logs details and returns a generic 500.
Invalid input is an expected outcome returned as a Result and shown as a 400. Real failures throw and are caught by one global handler that logs details and returns a generic 500.

Real-World Examples

  • On 4 June 1996 the maiden flight of the Ariane 5 rocket ended in self-destruction about 37 seconds after launch. The official inquiry found that a conversion of a 64-bit floating point value to a 16-bit integer overflowed and raised an unhandled exception in reused guidance software, which shut down the inertial reference systems. It remains a classic case of missing input range checks and inadequate handling of failures.
  • The TryParse methods on int and other numeric types have existed since .NET Framework 2.0 precisely because parsing user input with exceptions was measurably slow and clumsy. Microsoft's design guidelines for exceptions say not to use them for ordinary control flow, and many teams adopt a Result type for the same reason.
Key TakeawaysThrow exceptions for exceptional failures and programming errors, and return results for expected outcomes such as invalid input. Guard preconditions at the top of every public method. Use using for cleanup, catch only what you can handle, rethrow with a bare throw, and convert failures to generic responses at the API edge so internals never leak to clients.

Review Questions & Answers

Invalid input is an entirely normal, frequent outcome, so it should not be modeled as an exceptional event. Exceptions are much slower than returning a value, they blur the difference between user mistakes and real system faults, and they encourage using catch blocks as control flow. Returning a result keeps the failure explicit in the method signature so callers cannot forget to handle it.

A bare throw rethrows the current exception with its original stack trace intact, so you can see exactly where the failure began. Writing throw ex resets the stack trace to the current line, which discards the most useful diagnostic information. The bare form is almost always what you want.

The response exposes the stack trace, file paths, library versions, and sometimes SQL text or connection details to whoever made the request, which helps an attacker map the system and craft targeted attacks. Errors should be logged with full detail on the server and returned to the client as a generic message plus a correlation identifier, so support staff can find the log entry without the client learning anything sensitive.

It guarantees that the resource's Dispose method runs when the block exits, whether normally or through an exception. That prevents leaks of file handles, database connections, and sockets. In a busy server, a leaked connection on each failed request quickly exhausts the connection pool, after which every new request fails.