Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 132 ยท Error Handling

The ? Operator

Learn the Rust ? operator: propagating errors, automatic From conversion, using ? with Option, main returning Result, chaining calls and common errors.

In the last lesson you wrote error propagation by hand: a match on every fallible call, with an Err(e) => return Err(e) arm repeating itself. It works, but real functions make five or ten fallible calls, and the actual logic disappears under the plumbing. Rust's answer is a single character, the question mark, and it is probably the most-used piece of punctuation in everyday Rust code.

Put ? after an expression that has type Result and it means: if this is Ok, give me the value inside; if it is Err, return that error from the current function right now. That is all of it, plus one clever detail: on the way out the error is passed through the From trait, so one function can mix several kinds of error. This lesson explains exactly what ? expands to, how the conversion works, how it behaves with Option, how to use it in main, and the compile errors you will meet.

The idea: early return in one character

Here is the function from the previous lesson, rewritten:

Rust From six-line matches to a single ?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Read a.parse::<i32>()? as "parse it; if that fails, bail out with the error". The happy path now reads top to bottom with no noise, and the failure path is still fully explicit in the signature: the return type says ParseIntError can come out.

The expansion is roughly this (the real one goes through the Try machinery, but the behavior is the same for Result):

Rust
let first = match a.parse::<i32>() {
    Ok(value) => value,
    Err(error) => return Err(From::from(error)),
};

Two details hide in that expansion. First, ? is an expression: it evaluates to the unwrapped value, so you can chain it in the middle of a larger expression, such as read_config()?.port. Second, it contains return, which means it returns from the function it is written in, not from a block or a loop.

Chaining fallible calls

Because ? produces a value, whole pipelines of fallible steps become one readable line each. A method chain can have a ? after every link:

Rust A pipeline of fallible steps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first ? follows an Option converted with ok_or_else, which is the standard way to bring a missing value into a Result chain. The next two follow map_err, which adds context to an error (here it tells you whether width or height was wrong) before ? sends it upward. Notice that the last function parses twice only to show ? working in the middle of an expression; in real code you would store the rectangle first.

The conversion step: From

The detail that makes ? so flexible is the From::from(error) call in the expansion. If the function's error type is E2 and the failing expression's error is E1, then ? compiles as long as E2: From<E1>. When the types are identical, From is the identity conversion and costs nothing.

That means one function can propagate several different errors, as long as you have told Rust how to convert each into your error type. With an error enum, you implement From for each source error:

Rust ? converts errors with From

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

There are two ? operators on the parse calls with different source errors, and neither needed a map_err: ParseIntError becomes BadCount and ParseFloatError becomes BadRatio automatically, because the matching From implementations exist. The ok_or(...)? calls have an error that is already a ConfigError, so the identity conversion applies. The next lesson, custom error types, builds on exactly this pattern.

If no From implementation exists, rustc reports E0277 ("? couldn't convert the error to ConfigError") and adds a note that ConfigError needs to implement From<ParseIntError>. The fix is almost always to add that impl From, or to use map_err at that one call site.

Box: accepting any error

When you do not care to define an enum, such as in small programs or scripts, you can make the error type Box<dyn Error>. The standard library implements From<E> for Box<dyn Error> for every type E that implements Error, so ? works with any of them. The From<&str> and From<String> implementations let you even return a message directly.

Rust A boxed error accepts everything

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The price is that the caller can only print the error or inspect it dynamically with downcast_ref; it cannot match on variants. That trade-off is the heart of error design.

The ? operator and Option

? also works on Option. On Some(value) it gives you the value. On None it returns None from the function. This is perfect for lookups that can each come up empty:

Rust ? on Option

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The rule that stops you from mixing the two is strict: inside a function returning Option, you can use ? on an Option; inside a function returning Result, on a Result. You cannot use ? on an Option in a function that returns a Result (or the other way around) because there is no way to turn None into an error without a message. Convert explicitly with ok_or / ok_or_else (or .ok() in the other direction), as you saw in the earlier chain.

? needs the right return type

The most common beginner error is using ? in a function whose return type cannot carry the failure. main is the classic place, because its return type defaults to ():

Rust ? in a function that returns () (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

rustc stops with E0277 ("the ? operator can only be used in a function that returns Result or Option"), points at the signature of main and explains that ? cannot be used in a function that returns (). It even suggests the fix: change the return type to a Result. If you would rather not do that, handle the error right there with match or unwrap_or.

main can return a Result

fn main() is allowed to return Result<(), E>, where E implements Debug. Then ? works inside it. If main returns Err(e), the runtime prints Error: followed by the Debug form of e to standard error and exits with status 1. If it returns Ok(()), the exit code is 0.

Rust main returning a Result (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first two lines parse; the third (abc) fails inside ?, so main returns early. Notice that "finished" is never printed, the error appears on stderr, and the exit code is 1. This is a perfectly reasonable error-reporting strategy for small tools. For anything user-facing you will usually want a friendlier message, and for that you handle the error in main yourself. The details of exit codes are in the main function and exit codes.

Practical patterns

Collecting a Result. An iterator of Results can be collected into a single Result<Vec<_>, _>. Collection stops at the first Err and returns it:

Rust Collecting an iterator of Results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Context at the boundary. A bare ParseIntError says "invalid digit found in string" with no idea of which string. Add context with map_err where you still know it, then let ? carry the richer error upward.

Fall back instead of failing. ? is for propagation. If you can recover, use unwrap_or, or_else or a match instead.

try blocks. A nightly-only feature called try blocks would let you use ? inside a block and get a Result out of it without writing a helper function. It is not stable, so today you write a small closure or an inner function when you need that scoping, for instance let result = (|| -> Result<i32, ParseIntError> { Ok(a.parse::<i32>()? + b.parse::<i32>()?) })();.

? returns from the whole function. Inside a loop or a closure it does not "skip to the next iteration": inside a closure it returns from the closure, and inside a loop it leaves the function. To skip bad items, use match, continue, or .filter_map(|s| s.parse().ok()).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does value? do when value is Err(e) in a function returning Result<T, E2>?

    ? returns early from the whole function with the error, converted through From into the function's error type.
  2. 2. Why does fn main() { let n: i32 = "5".parse()?; } not compile?

    ? needs a return type of Result or Option (or another type implementing the right trait). () is not one, so rustc reports E0277.
  3. 3. What must exist for ? to turn a ParseIntError into your AppError?

    ? calls From::from on the error, so AppError: From<ParseIntError> is required. Without it you get an E0277 error.
  4. 4. A main declared as fn main() -> Result<(), Box<dyn Error>> returns an Err. What happens?

    The standard runtime reports the error through Debug on standard error and exits with a failure status.
  5. 5. Which is true about ? on an Option inside a function returning Option<T>?

    On Some(v) the expression is v; on None the function returns None immediately.

Summary

  • expr? unwraps Ok / Some, and returns early with Err / None otherwise. It replaces the six-line match and keeps the happy path readable.
  • On Err, the error goes through From::from, so a function can propagate several different error types if conversions exist; Box<dyn Error> accepts any Error.
  • ? is an expression and works in the middle of method chains; it always returns from the enclosing function or closure.
  • You cannot mix Option and Result with ?; convert with ok_or, ok_or_else or ok().
  • ? needs a compatible return type; main may return Result<(), E> where E: Debug, giving exit code 1 on error.
  • Collect an iterator of Results into Result<Vec<_>, _> to stop at the first failure.

Next: Custom Error Types