skip to content

You lead a C# shipping-quote library used by three services; what convention would you set for throwing, Try methods, result objects and catch (Exception) handlers?

level: principalimportance: should knowfreq 35%

answer

  1. three kinds of failure
  2. bugs throw, outcomes return
  3. no built-in union in C# 14
  4. one catch-all per process boundary
  5. analyzers enforce the rule

basics

~20 s

Throw for caller bugs and for failures the caller cannot prevent, return a Try method or a result object for outcomes callers branch on, and allow catch (Exception) only at each service's top-level boundary, which logs and decides. Enforce it with analyzers.

solid answer

~50 s

I'd sort the library's failures three ways. A caller bug, such as a null address or a negative weight, throws the `ArgumentException` family; nobody catches it specifically, they fix the code. An expected business outcome, such as an undeliverable address, is returned: a `TryQuote` method, or a result type such as an abstract `QuoteResult` record with sealed `Quoted` and `AddressRejected` cases. An environmental failure the caller cannot prevent, a carrier outage, throws a public `CarrierUnavailableException` that wraps the cause. C# 14 has no closed unions, so a `switch` over the result needs a discard arm or the compiler warns CS8509, and no result type may swallow `OperationCanceledException`. `catch (Exception)` is allowed only at each service's boundary, the request or message handler that logs and maps the failure, and CA1031, CA2201 and CA1032 are raised in `.editorconfig` so the rule is checked, not remembered.

code

csharp · 29 lines
csharp
using System.Diagnostics;
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

foreach (var postcode in new[] { "10115", "1011" })
{
    string text = Quoting.Quote(postcode, 2.5m) switch
    {
        Quoted q => $"Price {q.Price}",
        AddressRejected a => $"Fix the address: {a.Reason}",
        _ => throw new UnreachableException(),   // without this arm: warning CS8509
    };
    Console.WriteLine(text);
}

public abstract record QuoteResult;
public sealed record Quoted(decimal Price) : QuoteResult;
public sealed record AddressRejected(string Reason) : QuoteResult;

public static class Quoting
{
    public static QuoteResult Quote(string postcode, decimal weightKg)
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(weightKg);   // caller bug: still thrown
        if (postcode.Length != 5) return new AddressRejected("Postcode must have 5 digits.");
        return new Quoted(weightKg * 4.2m);
    }
}

go deeper

for a junior

Recall the split: exceptions for bugs and unexpected failures, a Try method or result for outcomes that happen in normal use, and no empty catch blocks.

for a middle

Explain the BCL convention of throw plus Try, why async methods cannot use out parameters, and how a record hierarchy with a switch expression models outcomes.

for a senior

Classify each failure of a real API into bug, expected outcome or environmental failure, keep cancellation propagating, and put broad catches only at service boundaries.

for a principal

Own the written convention and its enforcement: analyzer severities, documented exception contracts and a single result style, trading BCL familiarity against explicit outcomes for async, multi-outcome APIs.

## The decision A library shared by several services needs **one** answer to "how does this method tell me it failed?". Without it, one method returns `null`, another throws a generic `Exception`, a third returns an error string, and every caller writes its own defensive wrapper. The convention below follows the base class library where it can and adds a result type only where it pays. ## Three kinds of failure | Kind | Quote-library example | Mechanism | What the caller does | |---|---|---|---| | Caller bug | `null` address, weight of `-1` | throw `ArgumentNullException` / `ArgumentOutOfRangeException` | fixes the code; nobody catches it specifically | | Expected outcome | address cannot be delivered to | return: `TryQuote(...)` or a `QuoteResult` | branches on it in normal flow | | Environmental failure | carrier API unreachable | throw `CarrierUnavailableException` wrapping the cause | catches it where it can retry or degrade | The middle row is the only one that changes per codebase. The BCL answers it with the **Try pattern**, `bool TryX(..., out T result)` next to a throwing `X`, and that is the right default for a single expected failure with no extra data. A **result object** is better when: - there are **several outcomes** a caller handles differently, such as rejected address, unsupported destination or over the weight limit; - each outcome **carries data**, such as the reason or a suggested correction; - the method is **async**, because C# does not allow `out` parameters on async methods (CS1988), so `Task<bool> TryQuoteAsync(out Quote)` cannot be written. ## What C# 14 gives a result type, and what it does not - **Records** make the cases short: `public abstract record QuoteResult;` and `public sealed record AddressRejected(string Reason) : QuoteResult;`. - **Switch expressions** with type patterns consume them, but the compiler cannot prove a class hierarchy is complete: another assembly can derive from a public abstract record. Without a discard arm, SDK 10.0.401 warns `CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered.` A team convention is `_ => throw new UnreachableException()`. Union types and closed hierarchies are C# 15 preview features, not something C# 14 offers. - **The BCL has no general-purpose `Result<T>` type**, so the library defines its own small types or adopts one package for every service. - **Discipline the type cannot enforce**: a caller can ignore a returned result, while an unhandled exception cannot be ignored silently. ## Where catch (Exception) is allowed 1. **At a process or request boundary**: the top of a background worker's loop, a message handler, the host's request pipeline. It logs the whole exception, maps it to a response or a dead-letter decision, and lets the next message proceed. 2. **Nowhere inside the library.** A broad catch there turns a `NullReferenceException` into a fake "carrier unavailable" or swallows it, which hides bugs from all three services. 3. **When it rethrows**, a broad catch is fine: CA1031 accepts a `catch` whose last statement rethrows, such as cleanup followed by `throw;`. 4. **Never to convert cancellation.** `OperationCanceledException` must keep propagating, or a deliberate cancel becomes a failure result. ## Enforcing it - Raise **CA1031** (catching general exception types), **CA2201** (throwing reserved or general types), **CA1032** (standard constructors) and **CA1064** (public exceptions) to warnings in `.editorconfig`; all four are off by default in .NET 10. A boundary class that is allowed its catch-all carries a justified suppression. - Document every exception a public method throws with `<exception cref="...">` XML tags, because the exception types are part of the contract and must not change between versions. - Keep the expected outcomes in the method's return type, so they show up in the signature rather than in a wiki page. ## The trade-offs a lead weighs - **Consistency with the BCL** favours throw plus Try; every C# developer already reads `int.TryParse` and `Dictionary<TKey,TValue>.TryGetValue` that way. - **Explicit outcomes** favour result objects in async, multi-outcome APIs, at the price of an allocation per call for a record result and a discard arm in every switch. - **Performance** only decides hot paths: a throw costs far more than a return, so an outcome that happens on a large share of calls should never be an exception. - **Mixing** is normal and fine if the rule is written down: results for business outcomes, exceptions for bugs and outages, one catch-all per boundary.

  • Why does a switch over a sealed set of record cases still warn CS8509 in C# 14?
    The cases are sealed, but the public abstract base is not: any assembly can declare another type derived from `QuoteResult`, so the compiler cannot prove the listed arms cover every value. Add `_ => throw new UnreachableException()`. Union types and closed hierarchies, which would let the compiler check exhaustiveness, are only C# 15 preview features.
  • Where exactly may a catch (Exception) live in this design?
    At the boundary of each consuming service: the top of a message handler or worker loop, or the host's request pipeline, where the exception is logged with its full chain and turned into a response or a retry decision. Inside the shared library, broad catches are banned unless they rethrow, and CA1031 is raised to a warning so a new one is noticed in review.

  • Returns a result object for null arguments and other caller bugs
  • Catches Exception inside the library and returns a generic failure result
  • Converts OperationCanceledException into a failure result
  • Assumes the compiler checks exhaustiveness over an abstract record hierarchy
  • Throws for an outcome that occurs on a large share of calls

Assumes C# 14 on .NET 10; union types and closed hierarchies are C# 15 preview features, so a result hierarchy still needs a discard arm in switch expressions.