skip to content

What happens when a Rust program whose `main` is declared `fn main() -> Result<(), Box<dyn Error>>` returns an `Err` through `?`?

level: middleimportance: should knowfreq 58%

answer

  1. main can return Result
  2. the Termination trait
  3. printed with Debug, not Display
  4. failure exit code

basics

~20 s

Through std's Termination impl for Result, the runtime prints Error: followed by the error's Debug form to stderr and exits with ExitCode::FAILURE, status 1 on Unix and Windows. Locals in main are dropped normally first; nothing panics.

solid answer

~40 s

`main` may return any type that implements `std::process::Termination`. For `Result<T, E>`, std requires `T: Termination` and `E: Debug`, and its `report` method handles `Err(err)` by printing `Error: {err:?}` to stderr and returning `ExitCode::FAILURE`, which is `EXIT_FAILURE`, 1 on Unix and Windows. So `?` in `main` behaves like `?` anywhere: `main` returns early, its locals are dropped, and the runtime turns the `Err` into an exit status. Two traps follow. The message uses `Debug`, so an `io::Error` prints as `Os { code: 2, kind: NotFound, ... }` and a `String` prints with quotes. And the error type needs `Debug`, not `std::error::Error`. For a `Display` message or a custom exit code, return `std::process::ExitCode` (stable since Rust 1.61) and print the error yourself.

code

rust · 14 lines
rust
use std::error::Error;
use std::fs;

fn read_port(path: &str) -> Result<u16, Box<dyn Error>> {
    let text = fs::read_to_string(path)?; // io::Error -> Box<dyn Error>
    let port: u16 = text.trim().parse()?; // ParseIntError -> Box<dyn Error>
    Ok(port)
}

fn main() -> Result<(), Box<dyn Error>> {
    let port = read_port("missing.conf")?;
    println!("connecting on port {port}");
    Ok(())
}

go deeper

for a junior

Recall that main may return Result, which lets you use ? in main; an Err ends the program with an error message and a failing exit status.

for a middle

Explain the Termination impl for Result: Debug formatting to stderr, ExitCode::FAILURE, and the E: Debug bound that makes Result<(), String> legal.

for a senior

Show you know what users and scripts see: Debug output is noisy, so production CLIs print Display text and return a deliberate ExitCode while letting destructors run.

for a principal

Agree a convention for binaries, a run function plus an ExitCode main and documented exit statuses, so tooling and scripts can rely on failures being reported consistently.

## `main` and the `Termination` trait A Rust binary's `main` does not have to return `()`. It may return any type that implements **`std::process::Termination`**, a trait with a single method, `report(self) -> ExitCode`, whose result becomes the process exit status. std implements it for: - `()`, which reports `ExitCode::SUCCESS`; - `ExitCode` itself, which reports whatever code it holds; - `!` and `Infallible`, for a `main` that never returns normally; - `Result<T, E>` where `T: Termination` and `E: fmt::Debug`. The last impl is what makes `fn main() -> Result<(), Box<dyn Error>>` legal. Returning `Result<(), E: Debug>` from `main` has been allowed since Rust 1.26; `ExitCode` and the `Termination` trait became stable APIs in Rust 1.61. ## What happens on `Err` The `Result` impl in std's `process` module reads, in effect: ```rust match self { Ok(val) => val.report(), Err(err) => { // prints to stderr eprintln!("Error: {err:?}"); ExitCode::FAILURE } } ``` (The real code uses an internal stderr helper rather than `eprintln!`, but the format string is `"Error: {err:?}"`.) So when a `?` inside `main` hits an error: 1. `?` converts the error with `From::from` into `Box<dyn Error>` and `main` returns `Err(...)`. 2. As `main` returns, its locals are **dropped normally**, so destructors run and buffered writers can flush. 3. The runtime calls `report`, which prints `Error: ` followed by the error's **`Debug`** form to stderr. 4. The process exits with `ExitCode::FAILURE`, which std defines as the platform's `EXIT_FAILURE`, 1 on Unix and Windows. No panic is involved: there is no "thread 'main' panicked" message and no backtrace. ## The `Debug` trap Because the format is `{err:?}`, the output is the developer-facing form: | Error value | What is printed | |---|---| | `io::Error` for a missing file | `Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }` | | `String` such as `"no port in config"` | `Error: "no port in config"` (with the quotes) | | A derived-`Debug` struct | its struct syntax, field by field | A `Box<dyn Error>` adds nothing of its own: `Box`'s `Debug` impl delegates to the boxed value, which is why the `io::Error` inside shows its struct form. That is fine for a developer tool. For an end-user CLI, where the `Display` text ("No such file or directory (os error 2)") reads better, handle the error yourself. ## The bound is `Debug`, not `Error` `Termination for Result<T, E>` asks only for `E: Debug`. Consequences: - `fn main() -> Result<(), String>` compiles, since `String` is `Debug`, even though `String` does not implement `std::error::Error`. - A plain `struct ConfigError;` without `#[derive(Debug)]` fails with E0277, "`ConfigError` doesn't implement `Debug`", plus the note "required for `Result<(), ConfigError>` to implement `Termination`". - `Box<dyn Error>` is the conventional choice not because `main` needs `Error`, but because `?` converts every `Error` type into it. ## Controlling the message and the exit code Since Rust 1.61, a common pattern is a fallible `run` function plus a `main` that returns `ExitCode`: - `run() -> Result<(), Box<dyn Error>>` holds the logic and uses `?` freely. - `main() -> ExitCode` matches on `run()`, prints `eprintln!("error: {e}")` with `Display`, and returns `ExitCode::SUCCESS` or a chosen code such as `ExitCode::from(2)`. This keeps destructors running, unlike `std::process::exit`, which terminates the process at once. Its documentation notes that "no destructors on the current stack or any other thread's stack will be run", and it recommends returning a `Termination` type from `main` instead. ## A worked example: a CLI that cannot find its config A tool calls `read_port("missing.conf")?` from a `main` that returns `Result<(), Box<dyn Error>>`. The file does not exist, `fs::read_to_string` fails, both `?` operators propagate, and the terminal shows `Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }` with exit status 1. A shell script running `tool && deploy` stops there, which is the point of a non-zero exit, and `echo $?` right after the run shows the 1. Switching to the `run` and `ExitCode` pattern turns the same failure into `error: No such file or directory (os error 2)` with exit status 2.

  • Can `main` return `Result<(), E>` when `E` does not implement `std::error::Error`?
    Yes. std's `Termination` impl for `Result<T, E>` requires only `T: Termination` and `E: Debug`, so `Result<(), String>` works, and the `Err` prints as `Error: "..."` with quotes. A type without `Debug` fails with E0277, noting that `Debug` is required for `Result` to implement `Termination`.
  • How do you print the error with `Display` and pick the exit code yourself?
    Move the logic into a `run` function returning `Result<(), Box<dyn Error>>`, and make `main` return `std::process::ExitCode`, stable since Rust 1.61. Match on `run()`: on `Err(e)`, write `eprintln!("error: {e}")` and return a code such as `ExitCode::from(2)`; on `Ok`, return `ExitCode::SUCCESS`. Destructors still run, unlike with `process::exit`.

  • Returning Err from main panics the main thread with a backtrace
  • The error is printed using its Display implementation
  • main can return Result only if the error implements std::error::Error
  • The process still exits with status 0 because main returned normally
  • Calling process::exit(1) is equivalent, destructors included

Assumes Rust 1.99; main has returned Result<(), E: Debug> since 1.26, and ExitCode and the Termination trait have been stable since 1.61.