Module 6 · Nullability & error handling
6.2Result and the ? operator
How Rust returns errors as values instead of throwing them, how ? passes them up and converts them, and when unwrap and expect are the right call.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| A function that can fail | Throws; the signature doesn't say so | Throws; the signature doesn't say so | Returns Result<T, E>: Ok(value) or Err(error) |
| Pass the error to the caller | Do nothing; the exception keeps going up | Do nothing; the exception keeps going up | ? after the call |
| Handle the error | try / catch | try / catch | match, if let, or a method such as unwrap_or |
| Wrap an error in another | Catch and throw new Error(message, { cause }) | Catch and throw new SomeException(message, inner) | ? converts it with From, or map_err does it by hand |
| "This can't fail" | Don't catch | Don't catch | .expect("why"): panics with your message if it does |
| The program's entry point fails | Uncaught exception, stack trace, exit code 1 | Unhandled exception, stack trace, the process crashes | main returns Err: prints Error: … and exits with code 1 |
In TypeScriptC#, any function can throw, and nothing in its signature tells you. You find out from the docs, the source, or a crash. Rust has no exceptions. A function that can fail returns Result<T, E>: either Ok with the value or Err with an error. The caller can’t get the value without deciding what to do about the error, and the ? operator makes the most common decision, “pass it on to my caller”, a single character.
Errors are values
Result is an enum, like Option, but its “nothing” carries a reason:
enum Result<T, E> {
Ok(T),
Err(E),
}Like Option, it’s always in scope, so you write Ok(...) and Err(...) directly. Here’s a function that reads a port number from text, in both styles:
function parsePort(text: string): number {
const port = Number(text);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error(`not a port: ${text}`);
}
return port;
}
for (const text of ["8080", "http", "70000"]) {
try {
console.log(`port ${parsePort(text)}`);
} catch (error) {
console.log(`error: ${error instanceof Error ? error.message : String(error)}`);
}
}foreach (var text in new[] { "8080", "http", "70000" })
{
try
{
Console.WriteLine($"port {ParsePort(text)}");
}
catch (FormatException error)
{
Console.WriteLine($"error: {error.Message}");
}
}
static int ParsePort(string text)
{
if (!int.TryParse(text, out var port) || port < 1 || port > 65535)
{
throw new FormatException($"not a port: {text}");
}
return port;
}fn parse_port(text: &str) -> Result<u16, String> {
match text.parse::<u16>() {
Ok(port) if port > 0 => Ok(port),
_ => Err(format!("not a port: {text}")),
}
}
fn main() {
for text in ["8080", "http", "70000"] {
match parse_port(text) {
Ok(port) => println!("port {port}"),
Err(message) => println!("error: {message}"),
}
}
}Output
port 8080 error: not a port: http error: not a port: 70000
The signature -> Result<u16, String> says two things TypeScriptC# leaves unsaid: this function can fail, and when it does, you get a String explaining why. parse_port itself is built on text.parse::<u16>(), which returns a Result<u16, ParseIntError>; that’s why "70000", too big for a u16, fails without an explicit range check.
The caller uses match to handle both cases. It could not have used the u16 without one: a Result<u16, String> isn’t a number, just as an Option<u16> isn’t.
catch (error) gives you unknown under strict, because any value can be thrown, from any depth. Rust’s error has a type, and it comes from exactly one call.int.TryParse is the same idea in C# clothing: the failure is a return value (false), not an exception. Result goes one step further and carries the reason with it, so you don’t need a second “Try” version of every method.Mental model shiftThe signature tells you what can fail
A TypeScriptC# signature lists what a function returns when it works. A Rust signature also lists how it fails. You can read a call and know whether it can fail without opening the function, and the compiler won’t let a failure slip by unnoticed.
? passes the error up
Most of the time, the right response to an error is “I can’t handle this here; let my caller decide”. In TypeScriptC#, that’s what happens when you do nothing: the exception keeps going up the stack. In Rust, you write ? after the call:
type Address = { host: string; port: number };
function parseAddress(text: string): Address {
const at = text.indexOf(":");
if (at === -1) {
throw new Error(`missing ':' in ${text}`);
}
const port = parsePort(text.slice(at + 1)); // a throw here skips the rest
return { host: text.slice(0, at), port };
}
for (const text of ["example.com:8080", "example.com", "example.com:http"]) {
try {
const address = parseAddress(text);
console.log(`${address.host} port ${address.port}`);
} catch (error) {
console.log(`error: ${error instanceof Error ? error.message : String(error)}`);
}
}foreach (var text in new[] { "example.com:8080", "example.com", "example.com:http" })
{
try
{
var address = ParseAddress(text);
Console.WriteLine($"{address.Host} port {address.Port}");
}
catch (FormatException error)
{
Console.WriteLine($"error: {error.Message}");
}
}
static Address ParseAddress(string text)
{
if (text.Split(':', 2) is not [var host, var portText])
{
throw new FormatException($"missing ':' in {text}");
}
var port = ParsePort(portText); // a throw here skips the rest
return new Address(host, port);
}
record Address(string Host, int Port);struct Address {
host: String,
port: u16,
}
fn parse_address(text: &str) -> Result<Address, String> {
let (host, port) = text
.split_once(':')
.ok_or_else(|| format!("missing ':' in {text}"))?;
let port = parse_port(port)?; // an Err here returns it from parse_address
Ok(Address {
host: host.to_string(),
port,
})
}
fn main() {
for text in ["example.com:8080", "example.com", "example.com:http"] {
match parse_address(text) {
Ok(address) => println!("{} port {}", address.host, address.port),
Err(message) => println!("error: {message}"),
}
}
}Output
example.com port 8080 error: missing ':' in example.com error: not a port: http
parse_port(port)? means: if this is Err, return that error from parse_address right now; if it’s Ok, give me the value inside and carry on. The first ? does the same for the missing colon, after ok_or_else has turned the Option from split_once into a Result.
The control flow is the same as an exception passing through a function, with two differences: you can see each place the function can exit early, and the error travels as an ordinary return value, so nothing unwinds the stack.
Idiomatic RustHandle errors at the edges
Most functions should pass errors up with ?. Handle them in one place near the top, where you know what to do: show a message, retry, skip a bad line. That’s the same advice as “don’t catch what you can’t handle”, made cheap to follow.
When the error types differ: From and map_err
? returns the error from the current function, so the error must fit that function’s return type. parse_port happened to return String errors, like parse_address. Calling port.parse::<u16>() directly would give you a ParseIntError instead. You have two ways to make it fit.
From: ? converts automatically
Before returning the error, ? passes it through From::from. If your function’s error type implements From<ParseIntError>, the conversion happens with no extra code at the call. The usual design is an enum with one variant per kind of failure:
use std::num::ParseIntError;
enum AddressError {
MissingColon,
BadPort(ParseIntError),
}
impl From<ParseIntError> for AddressError {
fn from(error: ParseIntError) -> Self {
AddressError::BadPort(error)
}
}
fn port_of(text: &str) -> Result<u16, AddressError> {
let (_host, port) = text.split_once(':').ok_or(AddressError::MissingColon)?;
Ok(port.parse()?) // a ParseIntError becomes an AddressError through From
}
fn main() {
for text in ["example.com:8080", "example.com", "example.com:http"] {
match port_of(text) {
Ok(port) => println!("port {port}"),
Err(AddressError::MissingColon) => println!("error: no ':' in {text}"),
Err(AddressError::BadPort(error)) => println!("error: bad port ({error})"),
}
}
}Output
port 8080 error: no ':' in example.com error: bad port (invalid digit found in string)
The caller can now match on what went wrong, not just read a message, and the original ParseIntError is kept inside BadPort. That’s what TypeScript’s new Error(message, { cause }) aims for, except that the caller knows the possible errors from the type and doesn’t have to guess.That’s what C#‘s inner exceptions give you, except that the caller knows the possible errors from the type instead of from documentation. Writing these enums by hand gets repetitive; the next lesson shows thiserror, which writes the From and the error messages for you.
One From is built in and worth knowing: any type that implements the std::error::Error trait converts into Box<dyn std::error::Error>, a boxed “some error”, much like ErrorException as a catch-all type. The standard library’s errors, such as ParseIntError, all implement it, so a function returning Result<T, Box<dyn Error>> can use ? on every one of them. (AddressError above doesn’t implement the trait yet; the next lesson shows how.) You lose the ability to match on specific errors, which is fine in main, in small tools and in tests.
map_err: convert by hand
When there’s no From conversion, or you want to add detail, map_err changes the error and leaves an Ok alone. Then ? passes it on:
fn parse_port(text: &str) -> Result<u16, String> {
text.trim()
.parse()
.map_err(|error| format!("bad port {text:?}: {error}"))
}
fn main() {
for text in ["8080", "80 80", "99999"] {
match parse_port(text) {
Ok(port) => println!("port {port}"),
Err(message) => println!("error: {message}"),
}
}
}Output
port 8080 error: bad port "80 80": invalid digit found in string error: bad port "99999": number too large to fit in target type
It’s the Rust version of catching an exception and throwing a different one, for a single call. Here the function ends with the converted Result, so it needs no ?; in the middle of a function, you’d write .map_err(...)?.
unwrap and expect: when crashing is right
unwrap() gives you the Ok value, or panics (stops the program with a message) on Err. expect("why") does the same, with your message first. Panics are the subject of the next lesson; the short version is that they’re for bugs, not for failures you can expect. So unwrap and expect are fine in three places:
- Tests, where a panic fails the test and shows you the error.
- Prototypes and examples, where error handling would hide the point. Plan to replace them.
- Cases that truly can’t fail: the input is written in the code, or you checked it a line earlier.
const DEFAULT_PORT: &str = "8080";
let port: u16 = DEFAULT_PORT.parse().expect("DEFAULT_PORT is a valid port");
println!("port {port}");Output
port 8080
Prefer expect to unwrap. If it ever panics, the message starts with what you believed, followed by the error that proved it wrong, and it documents the assumption for the next reader. For anything that comes from outside the program (user input, files, the network, environment variables), return a Result instead.
Returning Result from main
? needs a function that returns a Result, and main can be one. With Box<dyn Error> as the error type, ? works on any error:
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let port: u16 = "8080".parse()?;
println!("port {port}");
Ok(())
}Output
port 8080
If main returns Err, Rust prints Error: followed by the error’s debug form ({:?}) to stderr, and the process exits with code 1. For a bad port, that’s this line:
let error = "http".parse::<u16>().unwrap_err();
println!("Error: {error:?}"); // what main prints, to stderr, when it returns this errorOutput
Error: ParseIntError { kind: InvalidDigit }That’s fine for a tool you run yourself, but it’s not a message for users. It plays the role of an uncaught exception in Node: the program stops with a non-zero exit code.It plays the role of an unhandled exception: the program stops with a failure exit code. The next lesson’s anyhow prints a readable message and the chain of causes instead.
Which one should I use?
Every call that returns a Result needs one of these. Pick by who should deal with the error:
| What | When | Why | How |
|---|---|---|---|
? | The caller is in a better place to decide. The default inside functions. | One character; every early exit stays visible. | let port = parse_port(text)?; |
? with a From impl | Errors of several types flow into one error enum. | The conversion is written once, not at every call. | impl From<ParseIntError> for AddressError, then port.parse()? |
.map_err(...)? | The types don’t convert, or you want to add context. | Changes only the error; the Ok passes through. | .map_err(|error| format!("bad port {text:?}: {error}"))? |
match | This is the place that knows what to do: show a message, retry, skip. | Handles every case, and the compiler checks you did. | match parse_port(text) { Ok(port) => ..., Err(message) => ... } |
if let Err(...), let Ok(...) = ... else | Only one outcome needs code. | Shorter than a match. | let Ok(port) = parse_port(text) else { continue; }; |
unwrap_or, unwrap_or_else, unwrap_or_default | A failure has a sensible fallback value. | One expression; the error is dropped on purpose. | parse_port(text).unwrap_or(8080) |
.ok() | You only care whether it worked, not why. | Turns Result<T, E> into Option<T>. | text.parse::<u16>().ok() |
expect("why") | Failure would be a bug: hard-coded input, a value you just checked, or a test. | Panics with your message and the error, at this line. | DEFAULT_PORT.parse().expect("DEFAULT_PORT is a valid port") |
unwrap() | Tests and quick prototypes. | Shortest, but a panic doesn’t say what you expected. | parse_port("80").unwrap() |
fn main() -> Result<(), Box<dyn Error>> | A small program or tool that should stop on the first error. | ? works in main on any error type. | End main with Ok(()). |
Rule of thumb: write ? by default, and handle errors with match at the top of the program, where you know what to tell the user. Add From impls (or thiserror) so ? converts errors for you, and map_err where it can’t. Keep expect for failures that would be bugs, and unwrap for tests.
As questions, asked in order:
Would an error here mean a bug: the input is in the code, you just checked it, or it's a test?
YesNo.expect("why it can't fail")In tests and quick prototypes,.unwrap()is fine too.Does a failure have a sensible fallback value?
YesNo.unwrap_or(value)or.unwrap_or_else(|error| ...)Is this the place that knows what to do about it: tell the user, retry, skip the item?
YesNomatch(orif let/let ... else)Usually near the top of the program, or in a loop over inputs.Otherwise: Pass it to the caller with
?, converting it with aFromimpl or.map_err(...)if the error types differ
Under the hood
? is shorthand for a match. These two functions do the same thing:
fn with_question_mark(text: &str) -> Result<u16, AddressError> {
let port = text.parse::<u16>()?;
Ok(port)
}
fn by_hand(text: &str) -> Result<u16, AddressError> {
let port = match text.parse::<u16>() {
Ok(value) => value,
Err(error) => return Err(From::from(error)),
};
Ok(port)
}So an error is an ordinary return value: no stack to unwind, no handler to search for, no stack trace captured. On the success path, a ? costs one check of the tag. An exception in TypeScriptC# carries a stack trace and has to search up the stack for a handler, which costs far more than a return. So Result is cheap enough for failures that happen all the time, like parsing user input.
Result is also marked #[must_use]. If you call a function that returns one and ignore the value, the compiler warns that the Result must be used, so an error can’t vanish just because you forgot to look. (let _ = save(); silences the warning on purpose, and the error with it.)
Common pitfalls
Common pitfall? can't convert the error
? converts errors through From, and only if a conversion exists. String has no From<ParseIntError>, so this fails:
fn parse_port(text: &str) -> Result<u16, String> {
let port = text.parse::<u16>()?;
Ok(port)
}Rust doesn't compile this: error E0277
error[E0277]: `?` couldn't convert the error to `String`
--> main.rs:2:35
|
1 | fn parse_port(text: &str) -> Result<u16, String> {
| ------------------- expected `String` because of this
2 | let port = text.parse::<u16>()?;
| --------------^ the trait `From<ParseIntError>` is not implemented for `String`
| |
| this can't be annotated with `?` because it has type `Result<_, ParseIntError>`
|
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
= help: the following other types implement trait `From<T>`:
`String` implements `From<&String>`
`String` implements `From<&mut str>`
`String` implements `From<&str>`
`String` implements `From<Box<str>>`
`String` implements `From<Cow<'_, str>>`
`String` implements `From<char>`The compiler says ? couldn’t convert the error to String. Convert it yourself with .map_err(|error| error.to_string())?, implement From for your own error type, or return Box<dyn Error>, which accepts any error.
Common pitfall? in a function that returns nothing
? returns the error from the current function, so that function must return a Result (or an Option, for None). A plain fn main() returns ():
fn main() {
let port: u16 = "8080".parse()?;
println!("port {port}");
}Rust doesn't compile this: error E0277
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> main.rs:2:35
|
1 | fn main() {
| --------- this function should return `Result` or `Option` to accept `?`
2 | let port: u16 = "8080".parse()?;
| ^ cannot use the `?` operator in a function that returns `()`
|
help: consider adding return type
|
1 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
2 | let port: u16 = "8080".parse()?;
3 | println!("port {port}");
4 + Ok(())
|Change the signature to fn main() -> Result<(), Box<dyn std::error::Error>> and end with Ok(()), or handle the error where it happens with match.
Common pitfallunwrap on input you don't control
"8080".parse::<u16>().unwrap() is fine; the input is in the code. line.parse::<u16>().unwrap() on a line a user typed is a crash waiting for the first typo. If the value comes from outside the program, return a Result and handle the Err.
Try it yourself
Exercise: port this to Rust
Port this to Rust. parsePerson reads a name:age line and throws on bad input. Write parse_person returning Result<Person, String>, with ? instead of exceptions, and handle the errors in main.
type Person = { name: string; age: number };
function parsePerson(line: string): Person {
const at = line.indexOf(":");
if (at === -1) {
throw new Error(`missing ':' in "${line}"`);
}
const ageText = line.slice(at + 1);
const age = Number(ageText);
if (ageText === "" || !Number.isInteger(age) || age < 0) {
throw new Error(`bad age "${ageText}"`);
}
return { name: line.slice(0, at), age };
}
for (const line of ["Ada:36", "Grace", "Linus:abc"]) {
try {
const person = parsePerson(line);
console.log(`${person.name} is ${person.age}`);
} catch (error) {
console.log(`error: ${error instanceof Error ? error.message : String(error)}`);
}
}foreach (var line in new[] { "Ada:36", "Grace", "Linus:abc" })
{
try
{
var person = ParsePerson(line);
Console.WriteLine($"{person.Name} is {person.Age}");
}
catch (FormatException error)
{
Console.WriteLine($"error: {error.Message}");
}
}
static Person ParsePerson(string line)
{
if (line.Split(':', 2) is not [var name, var ageText])
{
throw new FormatException($"missing ':' in \"{line}\"");
}
if (!uint.TryParse(ageText, out var age))
{
throw new FormatException($"bad age \"{ageText}\"");
}
return new Person(name, age);
}
record Person(string Name, uint Age);Expected output
Ada is 36 error: missing ':' in "Grace" error: bad age "abc"
Show a hint
Return Result<Person, String>. Use split_once(':') with ok_or_else(...)? for the missing colon, and parse() with map_err(...)? for the age. In main, match on the result.
Show a solution
struct Person {
name: String,
age: u32,
}
fn parse_person(line: &str) -> Result<Person, String> {
let (name, age) = line
.split_once(':')
.ok_or_else(|| format!("missing ':' in {line:?}"))?;
let age = age.parse().map_err(|_| format!("bad age {age:?}"))?;
Ok(Person {
name: name.to_string(),
age,
})
}
fn main() {
for line in ["Ada:36", "Grace", "Linus:abc"] {
match parse_person(line) {
Ok(person) => println!("{} is {}", person.name, person.age),
Err(message) => println!("error: {message}"),
}
}
}parse_person reads top to bottom: each ? hands an Err back to the caller, so the happy path needs no nesting. ok_or_else turns the Option from split_once into a Result, and map_err swaps the ParseIntError for a message. main is where the errors are handled, with one match per line.
Saved in this browser only.