Rust program to handle an error without terminating the program


Handle an error without terminating the program

Rust Programming Language


Handle an error without terminating the program


Problem


In this program, we will create a function to check a given number is EVEN/ODD and if the given number is not an EVEN number then we will return an error to the calling function and handle the error without terminating the program.


Input


// Rust program to handle an error 
// without terminating program

fn isEven(no:i32)->Result<bool,String> {
 if no%2==0 {
  return Ok(true);
 } else {
  return Err("Not an EVEN number".to_string());
 }
}

fn main(){
 let res = isEven(19);
 match res {
  Ok(msg)=>{
   println!("Number is even {}",msg);
  },
  Err(msg)=>{
   println!("Error: {}",msg);
  }
 }
 println!("End of the program");
}{codeBox}


Output


Error: Not an EVEN number
End of the program{codeBox}


Explanation


In the main() function, we called panic!() macro with the message "Error Occurred". That's why the program gets terminated immediately by calling println!() macro. The panic!() macro terminates the program immediately and provides feedback.


Post a Comment