Rust Error Handling

Posted Under: Programming, Rust, Rust Tutorial For Beginners, Tutorials on Oct 17, 2021
Rust Error Handling
Exceptions or Errors (in rust) is a state of a program when a piece of code does not execute as it should. It may be due to a resource that should be available at this time but is not. It may be due to a condition not fulfiled or a buggy network stream. But errors occur all the time. A good programmer is one who anticipates them and make logic to circumnavigation them, for example, while writing to a file check its permission or check if the file exists in the first place, if not make the file first and then write on it. Rust enforce the developer to make sure that all the contingencies are met before the program is compiled, this makes Rust less prone to an erroneous behaviour. Rust has two type of Errors recoverable errors, unrecoverable errors.

Unrecoverable Error in Rust

These are those Error, if occur, program execution is aborted. It is possible to explicitly throw an Unrecoverable Error using panic! macro, For instance
fn main() {
    panic!("Abandon Ship!");
But there are condition where such error are thrown by the library itself, for instance
fn main() {
    let mut primes=Vec::new();
    println!("Try getting 5th index:{:?}",primes[5]); //This will throw an Unrecoverable Error after which program execution is stopped.
Here the code is trying to access the fifth index of the Vector, which has only 4 items in it. In C language this is a major security loophole that is exploited, but Rust save us from arbitrary access un-authorized areas of the memory.

Recoverable Errors with Result

Most Error situaions can be handled by a contingency. Such conditions are not fatal for programm execution and can be dealt with.
use std::fs::File;

fn main() {
    let f = File::open("Cargo.toml");
    let _f = match f {
        Ok(file) => file,
        Err(error) => panic!("Problem opening the file: {:?}", error),
Here we are trying to get the handle of a file. There can be numerous ways that can lead to an Error condition, but we can avoid them by the check the return type of the Ok construct. Which if, returned type is of file then proceed otherwise trigger an error condition. You can check it by specifying a filename that does not exist, say NoCargo.toml.

A simpler version of the above program is
fn main() {
    let _f = File::open("Cargo2.toml").expect("Cannot find the file");
Use expect function that can eliminate extra code.