Logo

dev-resources.site

for different kinds of informations.

Result in Rust: another way of error handling

Published at
3/1/2024
Categories
rust
result
beginners
enum
Author
chanh_le
Categories
4 categories in total
rust
open
result
open
beginners
open
enum
open
Author
8 person written this
chanh_le
open
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

enum Article's
30 articles in total
Favicon
Mastering ENUMs in Go
Favicon
The 3 kinds of Enum in Rails
Favicon
Enhancing Enum Constants in Laravel with Description and Label Attributes
Favicon
Should I stay or should I go? Enums in TypeScript - error case study
Favicon
Effective Enum
Favicon
Result in Rust: another way of error handling
Favicon
How to convert a TypeScript built-in enum to a GraphQL enum
Favicon
Leveraging Enums in Angular: Enhancing Code Clarity and Reliability
Favicon
Typescript enum vs. "as const"
Favicon
Enum Fábrica Solitão em Java
Favicon
Implementing Enums in Golang
Favicon
Elixirでリストの最初の要素を取得
Favicon
[JS TS] How to create an object with keys based on enum
Favicon
Enum ou Enumerations no PHP
Favicon
Replacing If-Else Statements with Enums in Java
Favicon
Dart enhanced enum with custom values
Favicon
Working with Enums in Rust
Favicon
Modelando algoritmos complexos com enum
Favicon
Managing Task Status Transitions in TypeScript with Enums and Object Mapping
Favicon
TypeScript Enum's vs Discriminated Unions
Favicon
Strategy Pattern no Spring Boot Usando Enum
Favicon
Problem in C Pointer
Favicon
Merge TypeScript Enums
Favicon
Agora sim, o grande ganho do enum no Dart 2.17
Favicon
How to proper use ambient enum from Definition file
Favicon
O Poder da Classe Enum com métodos abstratos
Favicon
Refactoring code with the Strate Pattern
Favicon
🔥Input Enums for a better Development Experience 🔥 😋✂️
Favicon
O pequeno grande ganho do enum no Dart 2.15
Favicon
Typescript enums drawbacks and solutions

Featured ones: