Home » Rust Error handling

Rust Error handling

  • Error handling is a mechanism in which Rust determines the possibility of an error and acknowledge you to take some action before the code goes for compilation.
  • This mechanism makes the program more robust as it enables you to discover and handles the errors before you deploy the code for production.
  • Rust programming language does not contain the exceptions.

There are two types of errors in Rust:

  • Unrecoverable error:
  • Recoverable error

Rust Error handling

  • Recoverable Error: Recoverable errors are the errors which are reported to the user and user can retry the operation. Recoverable errors are not very serious to stop the process entirely. It is represented by Result<T,E>. Example of recoverable error is “file not found”.
    Where T & E are the generic parameters.
    T-> It is a type of value which is returned in a success case with an ‘OK’ variant.
    E-> It is a type of the error which is returned in a failure case with an ‘Err’ variant.
  • Unrecoverable Error: When the Rust reports an unrecoverable error, then the panic! macro stops the execution of a program. For example: “Divide by zero” is an example of unrecoverable error.

Recoverable Error vs Unrecoverable Error

Recoverable Error is an error that can be recovered in some way while Unrecoverable Error is an error that cannot be recovered in any way.

Let’s see a scenario of expected behavior:

In the above case, “100” is a string, so we are not confirmed whether the above case will work or not. This is the expected behavior. Therefore, it is a recoverable Error.

  • Unexpected behavior

Rust Error handling

assert!: An assert! is used when we want to declare something that it is true. If it is not correct and wrong enough, then the program stops the execution. It invokes the panic! , if the expression is not evaluated as true at the runtime.

Let’s see a simple example:

Output:

Rust Error handling

In the above example, the value of x is false and the condition within the assert! Macro is false. Therefore, an assert! Invoke the panic! at the runtime.

unreachable!: An unreachable! Macro is used for the unreachable code. This macro is useful as the compiler can not determine the unreachable code. Unreachable code is determined by the unreachable! at the runtime.

Let’s see a simple example:

Output:

Rust Error handling

In the above example, the value returned by the get_number() function is 5, and it is matched with each pattern, but it is not matched with any of the patterns. Therefore, the unreachable! macro calls the panic! macro.


You may also like