Skip to content

Latest commit

 

History

History
62 lines (42 loc) · 1.37 KB

7.md

File metadata and controls

62 lines (42 loc) · 1.37 KB

Error handling and Testing

Errors

Rust groups errors into 2 categories, recoverable and unrecoverable

  • recoverable errors rely on the Result type
  • unrecoverable errors use the panic macros

panic macro

panic!

the panic macro terminates the current thread. One the things than can cause a panic to occur is trying to perform out-of-bounds access of an array

let vec = vec![1];
// trying to access non-existent index
vec[10];

Result

Result is an enum that has 2 variables, Ok and Err.

enum Result<T, E>{
    Ok(T),
    Err(E)
}

this allows us to watch for potential panics in our code, and handle them differently. consider the following:

use std::fs::File;

let file: Result<File, Error> = File::open("somefile.txt");

let file: File = match file {
    Ok(file: File) => file,
    Err(error: Error) => panic!("a custom error description"),
    _ => panic!("we can't tell what happened"),
}

unwrap

if the Result of the program is Ok, the unwrap() will return the value inside the Ok for use, but if the Result of the program is Err, the unwrap() wil call panic for us.

let file2 = File::open("error.txt").unwrap();

expect

allows us to customize the error message. It allows to track the source of a panic much quicker.

let file3 = File::open("error.txt").expect("Error opening the file");