Back to course

File I/O & Error Propagation

Rust for Systems & Web3 Security

Professional Error Handling

Instead of expect, we should return a Result. This allows the caller to decide how to handle the error.

rust use std::fs::File; use std::io::{self, Read};

fn read_username() -> Result<String, io::Error> { let mut f = File::open("hello.txt")?; let mut s = String::new(); f.read_to_string(&mut s)?; Ok(s) }

The ? operator makes the code clean and safe.