Print an error message to the user and exit early:
1. You may use File::open("something.txt")?, try the following example (No panic, just print an error message):
use std::fs::File;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
let mut file = File::open("something.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
assert_eq!(contents, "Hello, world!");
Ok(())
}
Output (on error):
Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }
- Using
.expect("msg"): Panics if the value is an Err, with a panic message including the passed message, and the content of the Err (developer friendly, since shows the file name and line number):
use std::fs::File;
use std::io::prelude::*;
fn main() {
let mut file = File::open("something.txt").expect("failed to open file");
let mut contents = String::new();
file.read_to_string(&mut contents)
.expect("failed to read file");
assert_eq!(contents, "Hello, world!");
}
Output (on error):
thread 'main' panicked at 'failed to open file:
Os { code: 2, kind: NotFound, message: "No such file or directory" }',
src/main.rs:17:20
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
- No panic, just print an error message:
use std::fs::File;
use std::io::prelude::*;
fn main() {
let mut file = match File::open("something.txt") {
Ok(val) => val,
Err(e) => {
println!("failed to open file: {}", e);
return;
}
};
let mut contents = String::new();
file.read_to_string(&mut contents)
.expect("failed to read file");
assert_eq!(contents, "Hello, world!");
}
Output (on error):
failed to open file: No such file or directory (os error 2)