Home »
Rust »
Rust Programs
Rust program to handle an error without terminating the program
Rust Example: Write a program to handle an error without terminating the program.
Submitted by Nidhi, on November 25, 2021
Problem Solution:
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.
Program/Source Code:
The source code to handle an error without terminating the program is given below. The given program is compiled and executed successfully.
// 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");
}
Output:
Error: Not an EVEN number
End of the program
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.
Rust Miscellaneous Programs »