DEV Community

loading...

Discussion on: Error Handling in Rust programming language

aminmansuri profile image
hidden_dude • Edited

So if my function returns an error. Will the caller abort automatically? Where would it abort?

As I said: I'd like to understand better.

I don't know why its bulky boilerplate. In some programs there can be very few catch clauses in the code. Often its handled globally some way. Only when you care do you have to write some error handling.

I don't see how this is more work that Option.

As for computational expense I guess that would depend on the language. It would involve some for of long jump and stack unrolling. In itself that doesn't seem too expensive. Besides, when an exception is happening the computation part of your code is over, you're now dying, no longer doing computation.

Thread Thread
aminmansuri profile image
hidden_dude

So if you have the following function:

fn myFunc() {
   option opt1 = f1()
   option opt2 = f2()
   // do more
}

If f1() returns an error will that cause f2() not to execution and myFunc() to fail?

If the answer is no then I have no choice to write horrible code like:

fn myFunc() {
   option opt1 = f1()
   if (opt1.isError()) return ERROR;
   option opt2 = f2()
   if (opt2.isError()) return ERROR;
   // do more
}

Ie. we're back to prehistory of error checking where all I see is error checking code. Low signal to noise ratio.

Code like this looks super messy to me:

fn read_username_from_file() -> Result<String, io::Error> {
    let f = File::open("hello.txt");

    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    let mut s = String::new();

    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(e) => Err(e),
    }
}

The error handling is all mixed into the business logic.