Rust for C++

Error handling

Recoverable error (Result)

Rust
fn division(x: f64, y: f64) -> Result<f64, MathError> {
    if y == 0.0 {
        Err(MathError::DivisionByZero)
    } else {
        Ok(x / y)
    }
}

match division(5.0, 0.0) {
    Ok(ratio) => println!("Ratio: {:?}", ratio),
    Err(why) => println!("Error: {:?}", why)
}

Run

C++
float division(float x, float y) {
    if(y == 0.0) {
        throw MathError::DivisionByZero();
    } else {
        return x/y;
    }
}

try {
    cout << "Ratio: " << division(5.0, 0.0) << endl;
} catch (MathError::DivisionByZero &e) {
    cout << "Error: " << e.what() << endl;
}

Run

Non-recoverable error (panic)

Rust
panic!("Panic because block.number is 0");

Run

C++
exit(EXIT_FAILURE);

Run