try and catch in rust
fn main() {
let result = divide(10, 0);
match result {
Ok(value) => println!("Result: {}", value),
Err(err) => println!("Error: {}", err),
}
}
fn divide(a: i32, b: i32) -> Result<i32, &'static str> {
if b == 0 {
return Err("Division by zero");
}
Ok(a / b)
}
Explanation:
- The
main
function is the entry point of the Rust program. - Inside
main
, it calls thedivide
function with the values10
and0
, assigning the result to theresult
variable. - The
divide
function takes two parameters (a
andb
) and returns aResult
type, where the success case holds ani32
value and the error case holds a&'static str
(a static string). - Inside
divide
, it checks ifb
is equal to0
. If it is, it returns anErr
variant with the message"Division by zero"
. If
b
is not0
, it performs the divisiona / b
and returns anOk
variant containing the result.After calling
divide
inmain
, thematch
statement is used to pattern match against theresult
.- If
result
isOk
, it prints the result value usingprintln!
. - If
result
isErr
, it prints the error message usingprintln!
.