Zeeshan Adil
Book a call
← Rust for C# Engineers: From Garbage Collection to Ownership and Lifetimes

Chapter 9 of 16 · Part II, Working knowledge

Errors are values, and you have to look at them

by Zeeshan AdilUpdated 26 min read
Listen to this articleRust Result vs C# Exceptions: Error Handling with ? 25 min · read by an AI voice
0:00 / 25:00

Rust returns errors as values instead of throwing. How Result and the ? operator work, thiserror against anyhow, and how panic differs from an exception.

You will learn to return a useful error, propagate it with ?, and handle it at the application boundary. Follow the configuration-file example through one success and one failure before reading about error libraries or panic behavior.

Rust normally represents recoverable errors in the return type rather than throwing exceptions. A function that can fail says so explicitly:

Code
enum Result<T, E> {
    Ok(T),
    Err(E),
}

That is the whole mechanism. Result is an ordinary enum in the standard library, declared with the same enum keyword you would use for your own types. It has no compiler magic in it. You could write it yourself in four lines and it would work identically, right up until you wanted the ? operator, which is the one place the compiler knows the name.

Code
fn read_config(path: &str) -> Result<String, std::io::Error> {
    std::fs::read_to_string(path)
}

The caller cannot ignore it. There is no String to use until they take it out of the Result, and doing that means dealing with the error case. Not by convention or code review. The type does not fit otherwise.

There is one softer guard on top. Result carries a #[must_use] attribute in the standard library, so throwing the whole thing away without binding it produces a warning rather than silence:

Code
warning: unused `Result` that must be used
 --> src/main.rs:9:5
  |
9 |     read_config("app.toml");
  |     ^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: this `Result` may be an `Err` variant, which should be handled
  = note: `#[warn(unused_must_use)]` on by default
help: use `let _ = ...` to ignore the resulting value
  |
9 |     let _ = read_config("app.toml");
  |     +++++++

That wording comes straight from the annotation on the type, #[must_use = "this Resultmay be anErr variant, which should be handled"]. It is a warning, not an error, and unused_must_use is warn by default. Adding #![deny(unused_must_use)] at the crate root turns discarding a fallible call into a hard compile failure, which is closer to what people imagine Rust does out of the box. Worth doing, and worth knowing it is not the default.

What a C# signature does not tell you

Now the same function in C#:

Code
string ReadConfig(string path)

Nothing in that signature tells you anything about failure. File.ReadAllText can throw FileNotFoundException, DirectoryNotFoundException, IOException, UnauthorizedAccessException, PathTooLongException, NotSupportedException, ArgumentException, ArgumentNullException, and System.Security.SecurityException. Some of those share a base class. Some do not. The list lives in the XML documentation, which the compiler does not check against the implementation, and it is transitively incomplete the moment ReadConfig calls anything else.

Checked exceptions were Java's attempt to fix exactly this, and C# deliberately declined to copy them. Anders Hejlsberg gave the reasoning in a 2003 interview, The Trouble with Checked Exceptions: developers escaped the requirement rather than meeting it, declaring throws Exception on everything or writing empty catch blocks they intended to fill in later and never did. He also raised a versioning problem, that adding a checked exception to an existing method breaks every caller.

Rust's version works better for two reasons that are worth separating. First, the error is a return value rather than a second control-flow channel, so it composes with everything else in the language instead of needing its own rules. Second, the propagation syntax is one character, so the ceremony that killed checked exceptions never accumulates.

The question mark, and what it actually desugars to

Writing match at every call site would be unbearable, so there is an operator for the common case:

Code
fn load_settings(path: &str) -> Result<Settings, ConfigError> {
    let raw = std::fs::read_to_string(path)?;
    let parsed = serde_json::from_str(&raw)?;
    Ok(parsed)
}

Start with the simple model, because it is right most of the time: ? means if this is Ok, unwrap it and carry on, and if it is Err, return it from this function immediately. Early-return propagation, written once per fallible call.

That model is simplified in two ways, and both matter.

The first is the conversion. ? does not return the error unchanged. The Rust Reference spells it out: for a Result, Err(e) returns Err(From::from(e)). So std::io::Error becomes ConfigError on the way out, as long as you have said how. This is the piece that makes the whole design ergonomic instead of merely correct. Without it, every call site would need a map_err closure and the code would read worse than the exception version. With it, two unrelated error types flow into one enum and the call site stays a single character.

The second is what ? actually compiles to. Try is a lang item, and the operator expands to this:

Code
match core::ops::Try::branch(expr) {
    core::ops::ControlFlow::Continue(val) => val,
    core::ops::ControlFlow::Break(residual) =>
        return core::ops::FromResidual::from_residual(residual),
}

That is the reference's own description, and it is the current shape of the Try v2 design. branch splits the value into "keep going with this" or "stop, here is the leftover". The leftover is called the residual, and FromResidual decides what the enclosing function should return given one. For Result, the FromResidual implementation is where the From::from call lives.

The reason this matters practically is that ? is not hardcoded to Result. It also works on Option, on ControlFlow, and on Poll<Result<T, E>> and Poll<Option<Result<T, E>>>, which is why you see it inside hand-written Future implementations. The Try trait itself is still unstable, gated behind try_trait_v2, so you cannot implement it for your own types on stable Rust as of 1.98. Its tracking issue has been open since 2021.

Get the conversion wrong and the compiler is unusually direct about it:

Code
error[E0277]: `?` couldn't convert the error to `ConfigError`
  --> src/config.rs:12:44
   |
11 | fn load(path: &str) -> Result<ServerConfig, ConfigError> {
   |                        --------------------------------- expected `ConfigError` because of this
12 |     let raw = std::fs::read_to_string(path)?;
   |               -----------------------------^ the trait `From<std::io::Error>` is not implemented for `ConfigError`
   |               |
   |               this can't be annotated with `?` because it has type `Result<_, std::io::Error>`
   |
   = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait

The note is the useful line. It tells you the fix is not at the call site, it is a missing From implementation on your error type. Once you have read that note twice you will never be confused by ? again.

A worked example, in both languages

Read a file, parse it, validate it. Three fallible steps, three different kinds of failure, one error type at the boundary. Here is the whole thing in Rust, standard library only, no dependencies. Paste it into src/main.rs and cargo run will work.

Code
use std::error::Error;
use std::fmt;
use std::fs;
use std::num::ParseIntError;

#[derive(Debug)]
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
    pub max_connections: u32,
}

#[derive(Debug)]
pub enum ConfigError {
    Io { path: String, source: std::io::Error },
    MalformedLine { line_no: usize, text: String },
    BadNumber { key: &'static str, source: ParseIntError },
    Missing { key: &'static str },
    OutOfRange { key: &'static str, value: u32, max: u32 },
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConfigError::Io { path, .. } => write!(f, "could not read config file `{path}`"),
            ConfigError::MalformedLine { line_no, text } => {
                write!(f, "line {line_no} is not `key = value`: `{text}`")
            }
            ConfigError::BadNumber { key, .. } => write!(f, "`{key}` is not a number"),
            ConfigError::Missing { key } => write!(f, "required key `{key}` is missing"),
            ConfigError::OutOfRange { key, value, max } => {
                write!(f, "`{key}` is {value}, above the maximum of {max}")
            }
        }
    }
}

impl Error for ConfigError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            ConfigError::Io { source, .. } => Some(source),
            ConfigError::BadNumber { source, .. } => Some(source),
            _ => None,
        }
    }
}

fn read(path: &str) -> Result<String, ConfigError> {
    fs::read_to_string(path).map_err(|source| ConfigError::Io {
        path: path.to_string(),
        source,
    })
}

fn parse(raw: &str) -> Result<Vec<(String, String)>, ConfigError> {
    let mut pairs = Vec::new();
    for (i, line) in raw.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let (key, value) = line.split_once('=').ok_or_else(|| ConfigError::MalformedLine {
            line_no: i + 1,
            text: line.to_string(),
        })?;
        pairs.push((key.trim().to_string(), value.trim().to_string()));
    }
    Ok(pairs)
}

fn get<'a>(pairs: &'a [(String, String)], key: &str) -> Option<&'a str> {
    pairs
        .iter()
        .find(|(k, _)| k.as_str() == key)
        .map(|(_, v)| v.as_str())
}

fn validate(pairs: &[(String, String)]) -> Result<ServerConfig, ConfigError> {
    let host = get(pairs, "host")
        .ok_or(ConfigError::Missing { key: "host" })?
        .to_string();

    let port: u16 = get(pairs, "port")
        .ok_or(ConfigError::Missing { key: "port" })?
        .parse()
        .map_err(|source| ConfigError::BadNumber { key: "port", source })?;

    let max_connections: u32 = match get(pairs, "max_connections") {
        Some(text) => text.parse().map_err(|source| ConfigError::BadNumber {
            key: "max_connections",
            source,
        })?,
        None => 128,
    };

    if max_connections > 10_000 {
        return Err(ConfigError::OutOfRange {
            key: "max_connections",
            value: max_connections,
            max: 10_000,
        });
    }

    Ok(ServerConfig { host, port, max_connections })
}

pub fn load(path: &str) -> Result<ServerConfig, ConfigError> {
    let raw = read(path)?;
    let pairs = parse(&raw)?;
    validate(&pairs)
}

fn main() {
    let sample = "# demo config\nhost = 10.0.0.4\nport = eighty\nmax_connections = 512\n";
    fs::write("server.conf", sample).expect("writing the sample file into cwd should succeed");

    match load("server.conf") {
        Ok(config) => println!("loaded: {config:?}"),
        Err(e) => {
            eprintln!("error: {e}");
            let mut cause = e.source();
            while let Some(inner) = cause {
                eprintln!("  caused by: {inner}");
                cause = inner.source();
            }
        }
    }
}

With port = eighty that prints:

Code
error: `port` is not a number
  caused by: invalid digit found in string

Change it to port = 8080 and you get the success line instead:

Code
loaded: ServerConfig { host: "10.0.0.4", port: 8080, max_connections: 512 }

The important failure path is: parsing port produces an error, ? returns that error to the caller, and main prints it. No ServerConfig is returned on that path. Avoid replacing the failed parse with a default port unless silently accepting bad configuration is actually the policy you want.

The second line of the failure output comes from ParseIntError, reached through source(). That chain is the Rust equivalent of InnerException, and it is the reason it is worth storing the underlying error in your variant rather than flattening it into a string. Try port = 80800 and the cause changes to number too large to fit in target type, because u16 tops out at 65535 and ParseIntError distinguishes an invalid digit from an overflow.

The C# version, written the way a careful engineer actually writes it:

Code
using System;
using System.Collections.Generic;
using System.IO;

public sealed record ServerConfig(string Host, ushort Port, uint MaxConnections);

public class ConfigException : Exception
{
    public ConfigException(string message, Exception? inner = null) : base(message, inner) { }
}

public sealed class ConfigIoException : ConfigException
{
    public string Path { get; }
    public ConfigIoException(string path, Exception inner)
        : base($"could not read config file `{path}`", inner) => Path = path;
}

public sealed class MalformedLineException : ConfigException
{
    public int LineNumber { get; }
    public MalformedLineException(int lineNumber, string text)
        : base($"line {lineNumber} is not `key = value`: `{text}`") => LineNumber = lineNumber;
}

public sealed class BadNumberException : ConfigException
{
    public string Key { get; }
    public BadNumberException(string key, string text)
        : base($"`{key}` is not a number", new FormatException($"`{text}` is not a valid integer"))
        => Key = key;
}

public sealed class MissingKeyException : ConfigException
{
    public string Key { get; }
    public MissingKeyException(string key)
        : base($"required key `{key}` is missing") => Key = key;
}

public sealed class ValueOutOfRangeException : ConfigException
{
    public ValueOutOfRangeException(string key, uint value, uint max)
        : base($"`{key}` is {value}, above the maximum of {max}") { }
}

public static class ConfigLoader
{
    public static ServerConfig Load(string path)
    {
        string raw = Read(path);
        var pairs = Parse(raw);
        return Validate(pairs);
    }

    private static string Read(string path)
    {
        try
        {
            return File.ReadAllText(path);
        }
        catch (IOException ex)
        {
            throw new ConfigIoException(path, ex);
        }
        catch (UnauthorizedAccessException ex)
        {
            throw new ConfigIoException(path, ex);
        }
    }

    private static List<KeyValuePair<string, string>> Parse(string raw)
    {
        var pairs = new List<KeyValuePair<string, string>>();
        string[] lines = raw.Split('\n');
        for (int i = 0; i < lines.Length; i++)
        {
            string line = lines[i].Trim();
            if (line.Length == 0 || line.StartsWith('#')) continue;

            int sep = line.IndexOf('=');
            if (sep < 0) throw new MalformedLineException(i + 1, line);

            pairs.Add(new KeyValuePair<string, string>(
                line[..sep].Trim(), line[(sep + 1)..].Trim()));
        }
        return pairs;
    }

    private static ServerConfig Validate(List<KeyValuePair<string, string>> pairs)
    {
        string? Get(string key)
        {
            foreach (var p in pairs)
                if (p.Key == key) return p.Value;
            return null;
        }

        string host = Get("host") ?? throw new MissingKeyException("host");

        string portText = Get("port") ?? throw new MissingKeyException("port");
        if (!ushort.TryParse(portText, out ushort port))
            throw new BadNumberException("port", portText);

        uint maxConnections = 128;
        string? maxText = Get("max_connections");
        if (maxText is not null && !uint.TryParse(maxText, out maxConnections))
            throw new BadNumberException("max_connections", maxText);

        if (maxConnections > 10_000)
            throw new ValueOutOfRangeException("max_connections", maxConnections, 10_000);

        return new ServerConfig(host, port, maxConnections);
    }
}

public static class Program
{
    public static void Main()
    {
        try
        {
            Console.WriteLine(ConfigLoader.Load("server.conf"));
        }
        catch (ConfigException ex)
        {
            Console.Error.WriteLine($"error: {ex.Message}");
            for (Exception? inner = ex.InnerException; inner is not null; inner = inner.InnerException)
                Console.Error.WriteLine($"  caused by: {inner.Message}");
        }
    }
}

Given the same port = eighty input, that prints the same two lines the Rust version does, InnerException standing in for source():

Code
error: `port` is not a number
  caused by: `eighty` is not a valid integer

This is good C#. It is roughly the same length, it is arguably more readable in the Validate method because ?? and throw expressions are terse, and the exception hierarchy carries structured data the same way the Rust variants do.

Three differences are real, and none of them is about verbosity.

The signature. Result<ServerConfig, ConfigError> names both outcomes. ServerConfig Load(string path) names one. A caller reading the C# has to open the implementation, or trust a comment, to learn that ConfigException is the family it should catch.

The set is closed in one and open in the other. In Rust, ConfigError has five variants and that is all there will ever be until someone edits the enum. Matching on it exhaustively is checked. In C#, Load can also throw ArgumentException from File.ReadAllText when the path is empty. On .NET 9 that is System.ArgumentException with the message about the value not being an empty string, and it does not derive from IOException, so neither catch in Read sees it and it escapes the catch (ConfigException) at the caller. An empty string is exactly what an unset environment variable produces when it is read carelessly, so this is the ordinary path rather than an exotic one.

Adding a case is a compile error in one and silence in the other. Add a DuplicateKey variant to ConfigError and every downstream match that was exhaustive stops compiling:

Code
error[E0004]: non-exhaustive patterns: `ConfigError::DuplicateKey { .. }` not covered
  --> src/main.rs:14:11
   |
14 |     match err {
   |           ^^^ pattern `ConfigError::DuplicateKey { .. }` not covered
   |
note: `ConfigError` defined here
  --> src/config.rs:11:10
   |
11 | pub enum ConfigError {
   |          ^^^^^^^^^^^
...
17 |     DuplicateKey { key: String },
   |     ------------ not covered
   = note: the matched value is of type `ConfigError`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown

Add a DuplicateKeyException subclass and nothing breaks, nothing warns, and the new exception quietly falls through to whatever generic handler is furthest up the stack. Which behavior you prefer depends on whether you are the library author or the person on call.

That last point cuts both ways for library design. If your enum is public, adding a variant is a breaking change, because you just broke every exhaustive match in your users' code. The escape hatch is #[non_exhaustive] on the enum, which forces external matches to include a wildcard arm and makes future variants additive. Put it on public error enums by default. Leave it off internal ones, where the compile error is exactly the reminder you want.

thiserror in a library, anyhow in a binary

The hand-written Display and Error implementations above are mechanical. Every arm restates a field list the compiler already knows about, and the two impl blocks have to be edited in lockstep every time a variant changes. Almost nobody writes them by hand. thiserror is a derive macro that generates them from attributes:

Code
use thiserror::Error;

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ConfigError {
    #[error("could not read config file `{path}`")]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },

    #[error("line {line_no} is not `key = value`: `{text}`")]
    MalformedLine { line_no: usize, text: String },

    #[error("`{key}` is not a number")]
    BadNumber {
        key: &'static str,
        #[source]
        source: std::num::ParseIntError,
    },

    #[error("required key `{key}` is missing")]
    Missing { key: &'static str },

    #[error("`{key}` is {value}, above the maximum of {max}")]
    OutOfRange { key: &'static str, value: u32, max: u32 },
}

Same type, same behavior. The two hand-written impl blocks, twenty-five lines in the version above, are gone; the enum pays one attribute line per variant to get them back. The line count barely moves in an example this small. What changes is that the message and the source chain now live next to the variant they describe, so adding a variant is one edit instead of three, and a variant can no longer drift out of sync with a match arm you forgot to update. The #[source] attribute wires up the source() chain, and a field simply named source is picked up even without it. A #[from] attribute instead would also generate the From implementation that ? needs, which is how you get automatic conversion for variants that wrap exactly one foreign error. The crate's own documentation makes the important promise: it does not appear in your public API, so switching to or from hand-written implementations is not a breaking change.

anyhow is the other half of the pair, by the same author, and it solves the opposite problem. In a binary you usually do not want to match on error variants. You want a single type that any error can convert into, and you want to attach human context on the way up:

Code
use anyhow::{Context, Result};

fn main() -> Result<()> {
    let path = std::env::args().nth(1).context("usage: loader <config path>")?;
    let raw = std::fs::read_to_string(&path)
        .with_context(|| format!("reading config from {path}"))?;
    let config: ServerConfig = toml::from_str(&raw)
        .with_context(|| format!("parsing {path}"))?;
    println!("{config:?}");
    Ok(())
}

anyhow::Error is a boxed trait object, so anything implementing std::error::Error converts into it for free. That is what makes ? work across four unrelated error types in one function without a single From implementation. context and with_context add a layer to the chain, and the default report prints the whole chain. Use with_context when building the message costs something, because the closure only runs on the error path.

The split is not a matter of taste. anyhow's own README draws it: use anyhow when you do not care what error type your functions return and just want it to be easy, which is common in application code, and use thiserror when you are a library designing a dedicated error type so the caller gets exactly the information you chose.

DecisionLibraryBinary
Error typeyour own enumanyhow::Error
Cratethiserroranyhow
Whycallers need to match on the reasonnobody matches, they log and exit
Public APIyes, mark #[non_exhaustive]not applicable

A tradeoff of anyhow in a public library API is losing an explicit, exhaustively matchable error enum. Callers can still inspect concrete errors with downcast_ref; string matching is not required. Prefer a documented typed error when callers need to make decisions based on the reason.

fn main() -> Result<(), E> works because of the Termination trait: an Err return prints the error with its Debug formatting and exits with a failure code. Convenient, and slightly surprising the first time, since it is Debug and not Display.

Panic is not an exception

panic! exists, and it is for bugs. Index out of bounds panics. Integer overflow panics in debug builds. unwrap() on a None panics.

The Rustonomicon states the intended hierarchy plainly: Option when something might reasonably be absent, Result when something can go wrong and be handled, a thread panic when it cannot reasonably be handled, and an abort when something catastrophic happens. Four tiers, and the unwinding chapter is where they are written down.

The distinction the language is drawing is about invariants. Result is for things that can go wrong in the world: the file is missing, the JSON is malformed, the connection dropped. panic! is for things that should be impossible: a sorted array that is not sorted, a state machine in a state its author never wrote, a length that came back negative. In the first case the world surprised you. In the second, you were wrong about your own program, and continuing means computing on a false premise.

C# does not draw that line in the type system, which is why defensive try/catch is a common habit there and why catch (Exception) in a request handler feels reasonable. In Rust, catching a panic is not defensive. It is usually wrong, because the panic means something you believed is false, and the code that would handle it was written by the same person who was wrong.

Unwind versus abort

The default panic strategy unwinds: it walks back up the stack running every destructor on the way, then terminates the thread. You can catch that with catch_unwind, which is the closest thing to a catch block, and the standard library makes it deliberately awkward through the UnwindSafe bound so that you have to think about whether the data you are recovering is in a consistent state.

The alternative is abort. Set it per profile in Cargo.toml:

Code
[profile.release]
panic = "abort"

That maps to the -C panic codegen flag and is documented in the Cargo book. Aborting terminates the process immediately, runs no destructors, and lets the compiler drop all the landing pad code it would otherwise emit, which makes binaries smaller. Some targets have no choice: the docs note that NVPTX does not support unwinding and always aborts. Tests, benchmarks, build scripts and proc macros ignore the setting, because the test harness currently requires unwinding to report a failing test without taking the runner down with it.

Three details that catch people out. A panic inside a destructor that is already running during an unwind aborts the process, because there is no sensible way to unwind two things at once. Since Rust 1.81, an uncaught panic escaping an extern "C" function aborts rather than being undefined behavior, closing a long-standing soundness hole; if you genuinely need to unwind across an FFI boundary, the "C-unwind" ABI is the supported way. And panic = "abort" changes observable behavior in library code that relied on destructors running, so it is a decision for the top-level binary, not something a library should assume either way.

unwrap() and expect("message") extract the value and panic on failure. They get a bad reputation they only partly deserve. They are correct in tests, in prototypes, in main where there is nowhere left to propagate, in const contexts, and anywhere you can genuinely prove the case cannot happen. expect with a sentence explaining why it cannot happen is strictly better than unwrap, and the sentence should state the invariant, not restate the operation. expect("regex is a compile-time literal and was tested") earns its place. expect("unwrap failed") does not, and reviewers should say so.

The cost, and where it actually lands

The performance story here is real, and it is smaller and more specific than the enthusiasm suggests.

On the .NET side, throwing has genuinely been expensive. Microsoft's Exceptions and Performance guidance, reprinted from the 2008 Framework Design Guidelines, says a throwing member can be orders of magnitude slower, and it is where the Try-Parse pattern is written down. int.TryParse is Result with worse ergonomics and an out parameter.

Read that page carefully though, because it is not the blanket "avoid exceptions" people quote it as. It tells you not to use error codes over performance worries, and then offers Tester-Doer and Try-Parse as the two sanctioned ways to keep the fast path exception-free. The design position is that exceptions are the correct default and you buy your way out of them at specific hot spots. Rust starts from the other end.

.NET 9 made a substantial dent in it. Stephen Toub's Performance Improvements in .NET 9 describes two changes: the exception handling implementation ported over from Native AOT was switched on by default, and a global spinlock was removed from the exception path. His benchmark runs a thousand iterations, each awaiting a recursion ten levels deep that yields and then throws, catching at the top. It moves from 123.03 ms on .NET 8 to 54.68 ms on .NET 9, a reported ratio of 0.44.

Divide by the thousand iterations and that is about 123 microseconds per iteration before and 55 after. Do not read those as the cost of a throw. Each iteration also pays for eleven async frames and a Task.Yield, so the figure bundles the async machinery in with the exception, and a shallow synchronous throw is cheaper than this by a wide margin. The ratio is the durable part: a bit over twice as fast, and still expensive enough that you would not put it in a loop.

The spinlock detail is the one worth carrying. Toub calls the failure mode an exception storm: one failure causes another, CPU spikes on the overhead, other work starves and times out and throws in turn, and the thing feeds itself. A serialized structure on the exception path is what turns a rate of failures into a throughput collapse. That is a different shape of problem from "throwing is slow", and it is the shape that takes a service down.

A Result propagates through ordinary returns and branches rather than stack unwinding. That keeps the propagation mechanism simple, but constructing an error may still allocate, capture a backtrace, or perform expensive work. Measure the actual success and failure paths separately.

Rust's panic path, on the other hand, is not cheap. The Rustonomicon is explicit that the implementation is optimized for the case where you do not unwind, so being ready to unwind costs nothing, and actually unwinding is more expensive than in a language like Java. Panicking in a loop is a worse idea in Rust than throwing in a loop is in C#. It is just that nobody does it, because the type system pushed all the expected failures into Result.

There is a cost on the Rust side that people miss, and it is a layout cost rather than a control-flow one. Result<T, E> is a value returned by value, and its size is roughly the larger of T and E plus a tag. If your error enum grows a variant holding a String plus a PathBuf plus a backtrace, every fallible function in the crate now returns something wide, and can increase the space and data movement required for returns. Optimizers can eliminate copies, so a wide return type does not imply a full copy at every call. Clippy has a lint for exactly this, result_large_err, with a default threshold of 128 bytes. The fix is to box the error, Result<T, Box<ConfigError>>, or to box the fat variant's payload. In a hot parser this is measurable in a way that the error handling strategy itself never is.

Where C# genuinely wins

Two places, and they are not small.

A single boundary can catch everything, including bugs. ASP.NET Core middleware turns any exception, from any depth, in any library you did not write, into a 500 and a log line, and no function between the fault and the handler needs to mention it. Rust has no equivalent unless you either thread an error type through every layer or box everything into anyhow early. A panic deep in a third-party crate will take out your worker thread; the workaround is catch_unwind at the task boundary, which the async runtimes do for you but which is a deliberate act rather than a default.

Refactoring is cheaper. Adding a new failure mode three layers down in C# costs nothing at the intermediate layers. In Rust it costs an enum variant, a From implementation, and possibly a signature change in every function between. That is the price of the guarantee, and on a large codebase under time pressure it is a price you feel.

Exception habits that do not survive the port

Reaching for catch_unwind as a try/catch. It is not one. It does not catch Result errors, because those are not thrown. It is for FFI boundaries, thread supervisors, and test harnesses. If you find yourself wanting it in business logic, the thing you actually want is a Result.

Making one giant error enum for the whole crate. The C# instinct is a single exception base class per assembly. In Rust that produces an enum with thirty variants where every function returns all thirty, and callers cannot tell which four are actually possible. One error enum per module, converted upward with From, is the pattern that scales.

Stringly typed errors. Result<T, String> looks fine for a week. Then you need to distinguish retryable from fatal at a call site and you are matching on message text. Use an enum from the start, even a two-variant one.

Treating ? as a throw. It is a return. That means it runs no destructors beyond the normal scope exit, it cannot be intercepted between here and the caller, and if you are holding a lock guard when it fires, the guard drops on the way out exactly as it would at the end of the function. Usually that is what you want. Occasionally it is not, and the difference is invisible if you are picturing an exception.

Logging and returning. In C#, logging then rethrowing is a bad habit that produces duplicate entries. In Rust it is the same bad habit with a different syntax. Attach context with anyhow, or add a variant, and log once at the boundary.

Get the next deep dive by email

New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.

You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.

Written by Zeeshan Adil

I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.