Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.parse().expect("err") panics instead of handling a parse error

I am working my way through the Rust guessing game tutorial and am stuck. The tutorial states that

let mut guess = String::new();
let guess = "asdf";
let guess: u32 = guess.trim().parse().expect("err");

parses a String and expect evaluates the Result and stops in case of an error. So the output should be err, but I get:

thread 'main' panicked at 'err: ParseIntError { kind: InvalidDigit }', libcore/result.rs:945:5

I am using Rust stable.

Why doesn't my expect catch the error?

like image 254
KuSpa Avatar asked Oct 19 '25 04:10

KuSpa


1 Answers

It did. If you change the expect message to "oh no i am asploded", this is the output:

thread 'main' panicked at 'oh no i am asploded: ParseIntError { kind: InvalidDigit }', libcore/result.rs:945:5
note: Run with `RUST_BACKTRACE=1` for a backtrace.

expect is just unwrap with a custom message, and unwrap panics if it's used on a None or Err(_).

As for handling errors without panicking, you'll need to read the section on Recoverable Errors with Result in the book.

like image 192
DK. Avatar answered Oct 21 '25 23:10

DK.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!