You can live without Exceptions, If you are using RUST

If you are coming from Java background, where you have used Exception Handling extensively and you have started working on new language like RUST, which doesn’t support Exception Handling then you will be forced to think that does such kind of world really exists?

The Java story

Java provides full coverage to Exceptions and those are required to be handled with try-catch like construct. In Java, an Error “indicates serious problems that a reasonable application should not try to catch.” and an Exceptionindicates conditions that a reasonable application might want to catch.“.  Exceptions are further divided into two types: Checked and Unchecked. Checked exceptions are generally those from which a program can recover for exFileNotFoundException, ClassNotFoundException. If a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise, the program will give a compilation error.

Unchecked exceptions are not checked at compile time. It means if your program is throwing an unchecked exception and even if you didn’t handle/declare that exception, the program won’t give a compilation error. Most of the times these exception occurs due to the bad data provided by user during the user-program interaction. For ex: NullPointerExceptionArrayIndexOutOfBoundsException.

Errors are also unchecked exception & the programmer is not required to do anything with these. In fact, it is a bad idea to use a try-catch clause for Errors. Recovering from Error is not possible. We can recover from exceptions by either using try-catch block or throwing exceptions back to the caller. Working with such practices always gives an impression that code flow can jump somewhere else and you have to check the signature of every function being called to know.

RUST – fresh air

Rust solves the exception problem by not having exceptions.

Rust doesn’t support throwing exceptions, nor does it support catching them. Instead,

Rust provides two special generic enums:

I) Option<T> andResult<T, E> for recoverable errors and
II ) The panic! macro that stops execution when the program encounters an unrecoverable error.

This strategy is the most appreciated inside the functional programming world.

Rust does not use the concept of null\ nil\ undefined types to represent empty outputs. Instead it uses the concept of encapsulating values. Option<T> can have either Some(T) or no value/ None.

fn match_color(color: Option<&str>) {
    match color {
        Some("Red") => println!("Hey I got Red T-shirt"),
        Some(c) => println!("I don't like {} T-shirt", c),
        None => println!("No T-shirt"),
    }
}

In case of Result<T,E>, instead of accepting Some(T) or None, these options are replaced by Ok(T) and Err(E). Ok(T) basically works exactly like Some(T), encapsulating a generic value, while Err(E) is a wrapper for a value that represents the error.

fn parse_string_to_int(str: &str) {
    let i: Result<i32, ParseIntError> = str.parse::<i32>();

    match i {
        Ok(t) => println!("Here is parsed integer {}!", t),
        Err(e) => panic!("There was a problem {:?}", e),
    };
}

In above example, if you send invalid string, you will see below error message.

    Finished dev [unoptimized + debuginfo] target(s) in 0.31s
     Running `target/debug/hello-rust`
thread 'main' panicked at 'There was a problem ParseIntError { kind: InvalidDigit }', src/main.rs:13:19
note: Run with `RUST_BACKTRACE=1` for a backtrace.

The advantage of Result<T, E> and Option<T> is that you know exactly what you are getting.

In Java, It is possible to catch an OutOfMemoryError but  there is no way to recover. You may even get another `OutOfMemoryError while trying to catch it. Rust handles such errors in compile time, providing strict rules and checkings on everything the programmer does, like the ones related to memory management.

Reference:

Why Rust’s error handling is awesome

Error Handling

RUST Error Handling


Knoldus-blog-footer-image

Written by 

Ayush is the Sr. Lead Consultant @ Knoldus Software LLP. In his 10 years of experience he has become a developer with proven experience in architecting and developing web applications. Ayush has a Masters in Computer Application from U.P. Technical University, Ayush is a strong-willed and self-motivated professional who takes deep care in adhering to quality norms within projects. He is capable of managing challenging projects with remarkable deadline sensitivity without compromising code quality.

1 thought on “You can live without Exceptions, If you are using RUST

Leave a Reply

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!