1

You can live without Exceptions, If you are using RUST

 2 years ago
source link: https://blog.knoldus.com/you-can-live-without-exceptions-if-you-are-using-rust/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

You can live without Exceptions, If you are using RUST

Reading Time: 3 minutes

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 ex: FileNotFoundExceptionClassNotFoundException. 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 ) Thepanic! 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 OutOfMemoryErrorbut  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.

Explore more about this interesting topic “Live without Exceptions in Rust” in our upcoming webinar on 20th June, 2019 at 10:30 PM IST / 01:00 PM EDT. Register Here: https://bit.ly/2KduzSl

Reference:

Why Rust’s error handling is awesome

Error Handling

RUST Error Handling


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK