Industrial Training




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


    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:
"100".parse();  

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


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:
 fn main()  
{  
let x : bool = false;  
assert!(x==true);  
}  

Output:

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:
            enum Value  
{  
  Val,  
}  
  
fn get_number(_:Value)->i32  
{   
   5  
}  
fn find_number(val:Value)-> &'static str  
{  
  match get_number(val)  
  {  
    7 => "seven",  
    8=> "eight",  
    _=> unreachable!()  
  }  
}  
  
fn main()  
{  
  println!("{}", find_number(Value::Val));  
}  

Output:

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.




Hi I am Pluto.