Skip to content

Instantly share code, notes, and snippets.

@cy6erlion
Created December 10, 2019 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cy6erlion/67c52b4d16fedfe30e3445791413e254 to your computer and use it in GitHub Desktop.
Save cy6erlion/67c52b4d16fedfe30e3445791413e254 to your computer and use it in GitHub Desktop.

There are two types of errors:

  • Recoverable Errors
  • Unrecoverable Errors

Rust uses Result<T, E> for handling recoverable errors and the panic! macro to for unrecoverble errors.

Example

panic!

    panic!("crash and burn");
$ cargo run
   Compiling panic v0.1.0 (file:///projects/panic)
    Finished dev [unoptimized + debuginfo] target(s) in 0.25s
     Running `target/debug/panic`
thread 'main' panicked at 'crash and burn', src/main.rs:2:5
note: Run with `RUST_BACKTRACE=1` for a backtrace.

Result<T, E>

fn read_username_from_file() -> Result<String, io::Error> {
    let mut f = File::open("hello.txt")?;
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    Ok(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment