Handling errors and returning values
In this section, we'll learn about the built-in error handling support in the std::io
module. Handling recoverable errors in an appropriate manner makes Rust programs more robust.
In the code examples we've seen so far, we've used the unwrap()
function to extract the return value from the std::io
module methods and associated functions, such as Read
, Write
, BufReader
, and BufWriter
. However, this is not the correct way to handle errors. The std::io
module has a specialized Result
type that is returned from any function or method in this module that may produce an error.
Let's rewrite the previous example (of chaining readers) using the io::Result
type as the return value from the function. This allows us to use the ?
operator to directly pass errors back from the main()
function, instead of using the unwrap()
function:
use std::fs::File; use std::io::Read; fn main() -> std::io::Result<()> { ...