ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.