Skip to content

Instantly share code, notes, and snippets.

@hussachai
Created April 1, 2022 21:39
Show Gist options
  • Save hussachai/8e9b54eb5540c46cefb5651788f58137 to your computer and use it in GitHub Desktop.
Save hussachai/8e9b54eb5540c46cefb5651788f58137 to your computer and use it in GitHub Desktop.
Error Handling in Rust that Every Beginner should Know (recovering from a panic)
fn parse_to_f64(s: &str) -> f64 {
s.parse::<f64>().unwrap()
}
let result = std::panic::catch_unwind(|| {
println!("{}", parse_to_f64("12.34"));
});
assert!(result.is_ok());
let result = std::panic::catch_unwind(|| {
println!("{}", parse_to_f64("abcdef"));
});
assert!(result.is_err());
println!("You should see this")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment