DEV Community

Chanh Le
Chanh Le

Posted on • Edited on

Result in Rust: another way of error handling

I've just started learning Rust in 2 days. And the first thing I was surprised about was how Rust handles errors. I have used several different programming languages and I thought that the only way to handle errors or exceptions is catching them with try/catch statement. But you know what there is no try/catch at all in Rust. Yeah, that's true I swear!

Traditional way to handle error/exception

In other programming languages like Java, Python, we usually use the Exception Approach for handling errors. More specifically, we would throw exception or raise error when we want to signal the caller of our code that there is an error it needs to handle. And the caller would use try/catch statement to catch the error in order to handle it. That's the way of handling error that we all know I guess. But that's not true with Rust. So, how exactly does Rust handle error?

Java try/catch statement:

try {
  //  Block of code to try
  myFunction();
}
catch(Exception e) {
  //  Block of code to handle errors
}
Enter fullscreen mode Exit fullscreen mode

An Result always returned even in case of error

Yes, I say that. No mistake or typo here. But first, you need to know what Result is. Result in Rust is a built-in enum. It has two variants: Ok (for normal case) and Err (in case of any error occurred during runtime).
In case of no error, the caller of your code would receive a Result object of Ok variant. And if there was an error occurred, the Result object would be an Err variant.
And the caller would use the match statement to handle both variants.

Handling Result using match statement (Guessing Game):

let result = my_function() //guess.trim().parse()
let guess: u32 = match result {
    Ok(num) => num,
    Err(_) => continue,
};
Enter fullscreen mode Exit fullscreen mode

As you can see, Rust uses Result with Err variant to signal the caller of your code about error occurrences. The caller would handle the error using match statement. He could skip the error and retry if the error is recoverable, otherwise he could stop the program from running immediately using panic! marco.

Summary

Error handling in Rust uses a different approach compared to other common programming languages like Java, Python. There is nothing like try/catch statement in Rust. Instead, Rust provides a built-in enum called Result which would carry the error objects for us to handle using match statement.

What's next

Actually, there is another surprise to me about Rust, which is the concept of ownership. There's a complete new world for me to explore there. And that's what I would like to learn and write about next. So, stay tune!

References

Top comments (0)