Reputation: 4004
How to catch zero division errors without checking in advance?
In python, It is able to with try..except.
num1 = 3
num2 = 0
try:
num1 / num2
"""
I know that it should be check before divide but I want to do
without check in advance.
"""
except ZeroDivisionError:
print("Divided by zero")
I understand that checking the divisor is better.
But I am looking for a way to without checking in advance in Rust.
How do I do this?
Upvotes: 8
Views: 8622
Reputation: 29972
The safest choice is to use one of the various checked_div
functions, which return an Option<{number}>
.
fn do_calculation() -> Result<i32, &'static str> {
let num1 = 2;
let num2 = 0;
num1.checked_div(num2)
.ok_or_else(|| {
// produce some error value, using &'static str merely to reduce boilerplate
"division by zero"
})
}
Then at the called site, one would have the equivalent of the catch clause:
do_calculation().unwrap_or_else(|e| {
eprintln!("Oh no! {}", e);
});
These functions are still roughly equivalent to checking the divisor for 0 before performing the division proper.
See also:
Upvotes: 17