Rust: Smart Exception Handling with Result

0

Exception Handling:

When I started working on computer systems or especially programming, one thing I used to hear from colleague or friends "My code is broken". I have worked in such scenarios where the code is not working on production system and had to look into the logs for any Exception stack-trace or Errors statements that I can check. 

You must agree with me that intelligently reading and analyzing the logs is an art.


When working with Rust there are two types of Errors 

  1. panic! (Unrecoverable errors)
  2. Result<T,E> (recoverable errors)

panic!: 

Unrecoverable errors can occur anywhere. It may be because of bug in your code or in the library you are using. When such a situation occurs Rust calls Panic macro (! symbol is for macro). After calling panic, it tries to undo the changes that the program did (called as Unwinding) and then exit. But if its large program the Unwinding may take time, so you can simply ask program to abort by specifying below section in your cargo.toml.
[profile.release]
panic = 'abort'
  
you can also directly call panic:
fn main() {
   panic!("Unrecoverable error!");
}
  
when you run this program you see something like below:
C:\Sangam\workspace\error_handling>cargo run
   Compiling error_handling v0.1.0 (C:\Sangam\workspace\error_handling)
    Finished dev [unoptimized + debuginfo] target(s) in 0.77s
     Running `target\debug\error_handling.exe RUST_BACKTRACE=1`
thread 'main' panicked at 'Unrecoverable error!', src\main.rs:2:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\error_handling.exe RUST_BACKTRACE=1` (exit code: 101)
It tells you to run using `RUST_BACKTRACE=1` for more detailed information. you can run the same as below: 

For Windows use below command:
C:\Sangam\workspace\error_handling>set RUST_BACKTRACE=1
C:\Sangam\workspace\error_handling>cargo run
for Linux use below command:
C:\Sangam\workspace\error_handling>export RUST_BACKTRACE=1
C:\Sangam\workspace\error_handling>cargo run

Result<T,E>:

Rust Result type is nothing but a Enum with two variants OK(T) or Err(E). Because any operation will have two outcome, either the operation will be successful (i.e. OK) or there will be an error (i.e. Err).

Lets take below example:
you are trying to read a file. if the operation is successful you will print the content, if not it will throw some error.
use std::fs;
fn main() {
   let file_content = fs::read_to_string("hello.txt");

   // manually handling the error and success
    let _check = match file_content {
        Ok(file) => file,
        Err(_error) => {
            panic!("file not found");
        }
    };
}
  
There is shortcut way to achieve above things:
use std::fs;

fn main() {
  let file_content = fs::read_to_string("hello.txt")
    						.expect("file not found");

  println!("{:?}",file_content);
}
  
If the file is not present it will show your custom error message like below:
 Compiling error_handling v0.1.0 (C:\Sangam\workspace\error_handling)
    Finished dev [unoptimized + debuginfo] target(s) in 1.87s                                                           
     Running `target\debug\error_handling.exe`
thread 'main' panicked at 'file not found: Os { code: 2, kind: NotFound, message: "The system cannot find the file specified." }', src\main.rs:4:56  

Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*

Cookies Consent

This website uses cookies to offer you a better Browsing Experience. By using our website, You agree to the use of Cookies

Privacy Policy