Rust Error Handling

Error handling in Rustlang is primarily done using the Result enum and the panic! macro.

Errors are a fact of life in programming, and Rust is no exception. In fact, Rust tends to throw a lot of errors in order to keep code as safe and efficient as possible. Beginners in Rust often struggle with errors at first, and it can be a major obstacle toward adoption of the Rust language for teams and individuals alike.

This is why it’s important to learn about errors and integrate robust error handling into every project.

Recoverable and Unrecoverable Errors in Rust

Rust divides errors into two types:

  1. Recoverable errors: Errors that don’t cause a program to immediately fail.
  2. Unrecoverable errors: Errors that cause a program to immediately fail.

In Rust, these two error types are distinguished from each other and treated differently.

Recoverable Errors

Recoverable errors are often caused by non-bug related issues that need to be addressed or acknowledged.

For example, a file not found error is caused when a file is called but can’t be found in the specified location. This isn’t generally caused by a bug in the code; it’s just a problem that needs to be addressed for the program to run correctly.

In this case, we don’t need the program to stop entirely. We can address this type of an error using the Result<T, E> enum.

Unrecoverable Errors

Unrecoverable errors are often symptoms of an underlying bug that could cause a significant risk.

A common example of this if the code tries to access a location that is beyond the end of an array or vector. This could lead to a security vulnerability in which attacker could read out the contents of memory beyond the array or vector.

When it comes to unrecoverable errors, we want the program to terminate immediately in order to prevent any possible risk. This is done using panic!