Error Handling: Result, the ? Operator and Custom Errors
Handle failure the Rust way with Result, the question mark operator, parse errors, a custom error enum with Display and From, and see the exit code of a program that returns an error from main.
In this lesson you will
- Return and match on Result
- Propagate errors with ?
- Define a custom error enum
- Convert errors with From
About 28 minutes
Bad data must not crash the monitor
The sensors of Ines send lines of text such as “7,12.5”, a turbine id and a wind speed, and some lines arrive broken: an empty field, text instead of a number, a negative speed. A monitor that panics on the first bad line is useless, and one that ignores errors is dangerous. Rust has no exceptions. A function that can fail returns Result, which is either Ok(value) or Err(error), and the caller must deal with both before using the value, because the compiler will not let a Result be treated as a plain value.
Writing match on every Result would be tedious, so the question mark operator does the common thing: applied to a Result, it unwraps the Ok value, and on an Err it returns that error from the current function right away, converting it with the From trait when the types differ. The error type of a real program is usually an enum with one variant for each failure, plus an implementation of Display so that it can print a human-readable message. Implementing From for the underlying error types lets the question mark convert them automatically. A main function may itself return a Result: if it returns an Err, the program prints the error with Debug formatting and exits with status 1.
| Tool | Use |
|---|---|
| Result | Ok(value) or Err(error) |
| match / if let | Handle each case explicitly |
| ? | Return early on Err, convert with From |
| unwrap_or, unwrap_or_else | Provide a default |
| map_err | Change the error type |
| impl fmt::Display | Human-readable error text |
use std::fmt;
use std::num::ParseFloatError;
use std::num::ParseIntError;
#[derive(Debug)]
enum ReadingError {
MissingField,
BadId(ParseIntError),
BadSpeed(ParseFloatError),
OutOfRange(f64),
}
impl fmt::Display for ReadingError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ReadingError::MissingField => write!(f, "line needs an id and a speed"),
ReadingError::BadId(e) => write!(f, "bad turbine id: {}", e),
ReadingError::BadSpeed(e) => write!(f, "bad speed: {}", e),
ReadingError::OutOfRange(s) => write!(f, "speed {} is out of range", s),
}
}
}
impl From<ParseIntError> for ReadingError {
fn from(e: ParseIntError) -> Self { ReadingError::BadId(e) }
}
impl From<ParseFloatError> for ReadingError {
fn from(e: ParseFloatError) -> Self { ReadingError::BadSpeed(e) }
}
fn parse_line(line: &str) -> Result<(u32, f64), ReadingError> {
let mut parts = line.split(',');
let id_text = parts.next().ok_or(ReadingError::MissingField)?;
let speed_text = parts.next().ok_or(ReadingError::MissingField)?;
let id: u32 = id_text.trim().parse()?;
let speed: f64 = speed_text.trim().parse()?;
if !(0.0..=60.0).contains(&speed) {
return Err(ReadingError::OutOfRange(speed));
}
Ok((id, speed))
}
fn main() -> Result<(), ReadingError> {
let lines = ["7,12.5", "8, 9.0", "9", "x,5.0", "10,abc", "11,-3.0", "12,75", ""];
let mut good = Vec::new();
for line in lines {
match parse_line(line) {
Ok((id, s)) => { println!("ok {:?} -> turbine {} at {}", line, id, s); good.push(s); }
Err(e) => println!("fail {:?} -> {}", line, e),
}
}
println!("{} good lines, mean {}", good.len(), good.iter().sum::<f64>() / good.len() as f64);
let first = parse_line("5,40")?;
println!("question mark passed: {:?}", first);
let last = parse_line("6,oops")?;
println!("never printed: {:?}", last);
Ok(())
}
ok "7,12.5" -> turbine 7 at 12.5
ok "8, 9.0" -> turbine 8 at 9
fail "9" -> line needs an id and a speed
fail "x,5.0" -> bad turbine id: invalid digit found in string
fail "10,abc" -> bad speed: invalid float literal
fail "11,-3.0" -> speed -3 is out of range
fail "12,75" -> speed 75 is out of range
fail "" -> line needs an id and a speed
2 good lines, mean 10.75
question mark passed: (5, 40.0)
Error: BadSpeed(ParseFloatError { kind: Invalid })
Eight lines went through the parser, and two were accepted: line 7 with speed 12.5 and line 8 with speed 9. The other six each produced a different, readable error. The line “9” gave “line needs an id and a speed”, the line “x,5.0” gave “bad turbine id: invalid digit found in string”, “10,abc” gave “bad speed: invalid float literal”, and the two out-of-range lines gave “speed -3 is out of range” and “speed 75 is out of range”. The empty line produced the missing-field error as well. The monitor kept going and reported 2 good lines with a mean of 10.75.
Inside parse_line, the question mark did all the work. The call to parse in the id line returns a ParseIntError, the one in the speed line a ParseFloatError, and because the function returns ReadingError, the question mark converted each one automatically with the From implementations, wrapping them in BadId and BadSpeed. The ok_or call turned an Option into a Result, so that a missing field also uses the same error type. The caller sees one type, and Display gives every variant a clear message.
The last part shows main returning a Result. The call with “5,40” passed, and the call with “6,oops” failed, so the question mark returned the error from main, the line “never printed” did not run, and the program printed “Error: BadSpeed(ParseFloatError { kind: Invalid })” and exited with status 1, which a shell script or a service manager can test. The error output goes to stderr, the standard place for diagnostics.
Check by hand: the mean of the two accepted speeds is (12.5 + 9.0) / 2 = 10.75. The range 0.0..=60.0 includes 0 and 60, so -3 and 75 are rejected. The message for the negative number shows -3, because Rust prints the float -3.0 as -3 with the Display formatting, so do not parse your own messages.
Files, networks, users and sensors all produce bad data. Use unwrap and expect only for conditions that would be a bug in your own program, and say why in the expect message.
Give each module an error enum with a variant per failure, implement Display and From, and let ? do the conversions. For quick programs, Box accepts any error, and crates such as anyhow and thiserror reduce the code further, so check crates.io if you can use dependencies.
Every program in this lesson was compiled with rustc 1.97 (edition 2021) and run while the course was written. Rust releases every six weeks and its compiler messages improve all the time, so check doc.rust-lang.org for the current edition and wording. The program was run with its exit status checked, and stderr and stdout were captured together in the output block above.
Practice
Add a variant for a speed that is NaN. Make parse_line also accept a third field, the direction in degrees, between 0 and 360. Change main to return Box and see what changes in the error output.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does Result represent?
- Ok(value) or Err(error)
- A nullable value
- An exception
- A loop
Failure is a value.
What does ? do on an Err?
- Panics
- Ignores it
- Prints it
- Returns the error from the current function
Converted through From when needed.
Why implement From for an error type?
- To print errors
- For speed
- To clone it
- So ? converts other errors automatically
From is the conversion trait.
What happens if main returns Err?
- The program continues
- Nothing
- The error is printed and the exit status is 1
- A panic with a backtrace only
It is a clean failure.
What does ok_or do?
- Unwraps
- Prints
- Turns an Option into a Result
- Sorts
It supplies the error for None.
Summary
- Functions that can fail return Result, and the compiler forces the caller to handle it.
- ? returns early on Err and converts errors with From.
- A custom enum plus Display gives clear, structured errors.
- main can return Result; an Err means exit status 1.
Questions
Result or panic?
Use Result for failures that can happen in a correct program, such as bad input or a missing file. Use panic for bugs, such as a violated invariant.
Is ? like try/catch?
It is closer to an early return. The error travels up through ordinary return values, so every function on the way shows in its type that it can fail.
What are anyhow and thiserror?
Popular crates for application-level and library-level error handling. They need dependencies, so check crates.io and their documentation.
