Telmo Trooper
Telmo Trooper

Reputation: 5694

Which conditions would trigger error handling in "read_line" followed by "expect"?

When reading the input stream with read_line(), if you don't follow the statement with a .expect() the compiler will warn you that this `Result` may be an `Err` variant, which should be handled.

What I want to understand is what kind of situation will trigger such error handling.

I've tried piping my program into another one (./my_program | echo "hello") so I wouldn't have the chance to enter any input and would supposedly be able to see the error handling in action. To my surprise it actually led to a panic state:

thread 'main' panicked at 'failed printing to stdout: Broken pipe (os error 32)', src/libstd/io/stdio.rs:792:9

In this code from the book The Rust Programming Language, we specify a string which I believe should be printed when the program isn't able to read the input stream:

use std::io;

fn main() {
    println!("Guess the number!");

    println!("Please input your guess.");

    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .expect("Failed to read line");

    println!("You guessed: {}", guess);
}

How can I actually see that behavior in action?

Upvotes: 2

Views: 940

Answers (1)

mcarton
mcarton

Reputation: 30061

Let's follow the source:

Let's try this:

$ rustc a.rs # your program
$ echo "\x99" | ./a
Guess the number!
Please input your guess.
thread 'main' panicked at 'Failed to read line: Custom { kind: InvalidData, error: StringError("stream did not contain valid UTF-8") }', src/libcore/result.rs:997:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

Upvotes: 7

Related Questions