Skip to content

Latest commit

 

History

History
72 lines (70 loc) · 1.45 KB

21.error-handling.md

File metadata and controls

72 lines (70 loc) · 1.45 KB

Error handling

types of errors

  • recoverable
fn exit(x:i32){
    if(x==0){
        panic!("we got a 0");   
    }
    println!("things are fine");
}
fn main() {
    exit(1);
    exit(0);
}
  • non-recoverable
fn main() {
    let v = vec![1,2];
    v[50]; 
}
  • set RUST_BACKTRACE=1 or export RUST_BACKTRACE=1 to see stacktrace
  • Error handling in code can be done using Result & Option type, since rust don't have something like null
enum Result<T, E> {
    Ok(T),
    Err(E)
}
enum Option<T> {
    Some(T),
    Hone
}
  • real-world example (off-course there are special function like expect() unwrap() )
use std::io::ErrorKind;
use std::fs::File;

fn main() {
    let f = File::open("file.txt");
    let f = match f {
        Ok(file) => file,
        Err(ref error) if error.kind() == ErrorKind::NotFound => {
            match File::create("file.txt") {
                Ok(fc) => fc,
                Err(e) => {
                    panic!("cannot create file : {:?}", e)
                }
            }
        }
        Err(error) => {
            panic!("cannot not open the file: {:?}", error)
        }
    };
}
  • ? operator similar to typescript
use std::fs::File;
use std::io;
use std::io::Read;

fn read_file()-> Result<String, io::Error> {
    let mut s = String::new();
    let mut f = File::open("file.txt")?.read_to_string(&mut s)?;
    Ok(s)
}
fn main() {
    let f = File::open("file.txt")?;
}