Is there a way to catch "division by zero" errors without checking in advance?

Viewed 1831

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?

1 Answers

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;
    let out = 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:

Related