読者です 読者をやめる 読者になる 読者になる

Error Handling #4

https://doc.rust-lang.org/book/error-handling.html

use std::fs::File;
use std::io::Read;
use std::path::Path;

fn file_double<P: AsRef<Path>>(file_path: P) -> i32 {
    let mut file = File::open(file_path).unwrap(); // error 1
    let mut contents = String::new();
    file.read_to_string(&mut contents).unwrap(); // error 2
    let n: i32 = contents.trim().parse().unwrap(); // error 3
    2 * n
}

fn main() {
    let doubled = file_double("foobar");
    println!("{}", doubled);
}
$ cargo run
   Compiling 5_7_error_handling v0.1.0 (file:///Users/miura/work/git-work/exercises/The_Rust_Programming_Language/5_7_error_handling)
    Finished debug [unoptimized + debuginfo] target(s) in 1.38 secs
     Running `target/debug/5_7_error_handling`
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { repr: Os { code: 2, message: "No such file or directory" } }', ../src/libcore/result.rs:837
note: Run with `RUST_BACKTRACE=1` for a backtrace.
$ touch foobar
$ cargo run
    Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/5_7_error_handling`
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: Empty }', ../src/libcore/result.rs:837
note: Run with `RUST_BACKTRACE=1` for a backtrace.
$ echo 1 > foobar
(anaconda3-4.2.0) miura (master *) 5_7_error_handling $ cargo run
    Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/5_7_error_handling`
2