Sub topic 11
Returning Result from main
This chapter assumes you can write functions that return Result and use ? inside them. It also assumes you know what Box<dyn Error> is and have run a Cargo project. Here you will see how the error that ? produces at the top of a program becomes output and an exit code.
Why main needs a way to fail
Every error that ? propagates travels up the call stack until something handles it. In a command-line program, the last stop is main. If main returns (), you cannot use ? inside it, because there is nowhere to send the error. You would have to write a match around every fallible call, or call unwrap, which panics.
Rust lets main return a Result. The error then leaves main, the runtime reports it, and the process exits with a failure status. This makes main look like any other function that propagates errors.
The simplest form
use std::error::Error;
use std::fs;
fn main() -> Result<(), Box<dyn Error>> {
let text = fs::read_to_string("count.txt")?;
let count: u32 = text.trim().parse()?;
println!("count = {count}");
Ok(())
}Both ? operators work even though they produce different error types. io::Error and ParseIntError each convert into Box<dyn Error> through From, as the chapter on From conversion described. The success type is (), so the last line is Ok(()).
If count.txt does not exist, the program prints something like this to standard error:
Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }The process then exits with status 1. If the file contains abc, you get:
Error: ParseIntError { kind: InvalidDigit }Notice that this is the Debug form of the error, not the friendly Display message. That detail drives most of the design decisions in the rest of this chapter.
What the runtime does with your return value
The return type of main must implement the std::process::Termination trait. The runtime calls it after main returns, and it turns the value into an exit code.
The standard library implements Termination for these types:
| Return type of `main` | Behavior |
|---|---|
| `()` | Exit status 0. |
| `ExitCode` | Exit with the code you choose. |
| `!` | Never returns, for example an infinite loop. |
| `Result<T, E>` where `T: Termination` and `E: Debug` | `Ok(t)` uses the exit code of `t`. `Err(e)` prints `Error: {e:?}` to standard error and exits with status 1. |
The bound E: Debug is the important one. The error type does not need to implement Error or Display. Box<dyn Error> works because it is Debug. A plain String also works, but it prints with quotes:
fn main() -> Result<(), String> {
Err("something broke".to_string())
}Error: "something broke"The Debug output problem
Because the runtime uses {:?}, a custom error type that derives Debug prints its internal structure. With the ConfigError enum from the custom errors chapter, a bad port prints:
Error: BadNumber(ParseIntError { kind: InvalidDigit })That is accurate, but it is not what you would show a user. You have three ways to improve it.
Option 1: write Debug by hand
You can implement Debug so that it prints the human-readable message. This is legal because Debug has no required format.
use std::fmt;
struct AppError(String);
impl fmt::Debug for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
fn main() -> Result<(), AppError> {
let n: i32 = "x1"
.parse()
.map_err(|e| AppError(format!("bad number: {e}")))?;
println!("{n}");
Ok(())
}Error: bad number: invalid digit found in stringThis works, but it bends the meaning of Debug. Other code that logs the value with {:?} will also lose the structure. Use it for a small wrapper type that exists only for main.
Option 2: handle the error yourself
Keep main thin and move the real work into a function that returns Result. Then main decides how to print the error and which exit code to use. This is the approach most production programs choose.
use std::error::Error;
use std::fs;
use std::process::ExitCode;
fn run() -> Result<(), Box<dyn Error>> {
let text = fs::read_to_string("count.txt")?;
let count: u32 = text.trim().parse()?;
println!("count = {count}");
Ok(())
}
fn main() -> ExitCode {
match run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("error: {e}");
let mut source = e.source();
while let Some(cause) = source {
eprintln!(" caused by: {cause}");
source = cause.source();
}
ExitCode::from(2)
}
}
}This version prints the Display message, walks the chain of source() errors, and exits with status 2. ExitCode::SUCCESS is 0 and ExitCode::FAILURE is 1. ExitCode::from accepts a u8, so you can give different failures different codes that scripts can test.
Option 3: use a crate
The anyhow crate provides anyhow::Error, whose Debug output is a readable message followed by a "Caused by" list. A main that returns anyhow::Result<()> therefore prints a useful report with no extra code. A later chapter covers this.
Choosing a return type
| Situation | Suggested `main` signature |
|---|---|
| Quick script or example, you only need the program to stop on error | `Result<(), Box<dyn Error>>` |
| You want clean messages and specific exit codes | `fn main() -> ExitCode` with a `run()` function |
| A library-style error enum you already wrote, output format not important | `Result<(), ConfigError>` |
| You want readable reports with little code | `anyhow::Result<()>` |
Common mistakes
Using ? in a main that returns ()
This is the most frequent error. Suppose you write:
use std::fs;
fn main() {
let text = fs::read_to_string("count.txt")?;
println!("{text}");
}The compiler rejects it with error E0277, whose message begins:
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)The fix is to change the signature to fn main() -> Result<(), Box<dyn Error>> and end the body with Ok(()). Forgetting the final Ok(()) causes a different error: the body then evaluates to () where a Result is expected, which the compiler reports as a type mismatch.
Expecting a clean message from Display
New users often assume Error: ... shows the Display text. It does not. If you want that text, use option 2 or a crate.
Skipping destructors with process::exit
You might think of calling std::process::exit(1) from deep in the program. That function ends the process immediately and does not run destructors for values still alive on the stack. Buffered writers may not flush, and temporary files may not be removed. Returning from main unwinds normally, so values are dropped first. This is another reason to prefer returning an ExitCode or Err.
Returning an error type that is not Debug
The bound is E: Debug. If your custom error lacks #[derive(Debug)], the compiler reports that the trait bound Termination is not satisfied for your Result. Adding the derive fixes it. The Error trait already requires Debug, so any type that implements Error satisfies this.
Returning a value from Ok
Result<T, E> requires T: Termination, so T can be ExitCode as well as (). This lets a program choose its success code and still use ?:
use std::error::Error;
use std::process::ExitCode;
fn main() -> Result<ExitCode, Box<dyn Error>> {
let value: i32 = "42".parse()?;
if value > 40 {
return Ok(ExitCode::from(3));
}
Ok(ExitCode::SUCCESS)
}An Err still exits with status 1. An Ok uses the code you returned. This is useful for tools that report conditions such as "differences found" through the exit code, the way diff does.
Testing code that main calls
Keep most of your logic out of main. A function such as run() returns a Result and can be called from a unit test, where you can assert on the error value. A main that exits the process cannot be tested that way. This split also keeps main as the only place that decides how errors look to a user.
Exercise
A program has fn main() -> Result<(), Box<dyn Error>>. It parses the text "12x" with .parse::<i32>()?. What is printed to standard error, and what is the exit status?
Show answer
It prints Error: ParseIntError { kind: InvalidDigit } and exits with status 1. The runtime uses the Debug form of the error, not Display, and any Err from main gives status 1.
Exercise
You want a program that prints error: <Display message> to standard error and exits with status 2 on any failure, while still using ? in the main logic. How should you structure it?
Show answer
Put the logic in fn run() -> Result<(), Box<dyn Error>> and make fn main() -> ExitCode. In main, match on run(). On Ok(()) return ExitCode::SUCCESS. On Err(e) call eprintln!("error: {e}") and return ExitCode::from(2).