Rust alternatives to throwing Exceptions?


#1

Hi all,

I’m coming from Java and teaching myself Rust and like it a lot (bought the book last night, can’t wait for it to arrive!). One nice thing in Java is I can have method 1 call method 2 which calls method 3 which calls method 4 which calls method 5, and if an exceptional issue arises in method 5, nobody has to deal with it until it propagates up to method 1 (for exanple). In Rust I find myself returning Result constantly, and checking for errors in every single method, so I end-up writing a ton of boilerplate code. Even basic arithmetic operations can lead to NaN, inf, etc., which leads to combersome code.

Is there another, better strategy in Rust for allowing errors to occur in methods without forcing every caller of every method to check and deal with the error?

Thanks! :slight_smile:


#2

There’s a chapter in the book about errors, and especially note the ? operator that makes it really easy to propagate errors.

https://doc.rust-lang.org/book/second-edition/ch09-02-recoverable-errors-with-result.html#propagating-errors


#3

Thanks cuviper, that’s exactly what I was looking for! :slight_smile: