Exceptions
Error handling in the three languages.
C++
Rust
Java
double safe_div(int n, int d) throw(string)
{
if(d == 0)
throw string("Divide by zero");
return n/d;
}
int main(unused int argc, unused char **argv) {
try {
cout << safe_div(1, 0) << endl;
} catch(string &err) {
cerr << err << endl;
}
return 0;
}
fn safe_div(n: f64, d: f64) -> Result<f64, &'static str> {
if d == 0.0 {
return Err("Divide by zero");
} else {
return Ok(n/d);
}
}
fn main() {
match safe_div(1.0, 0.0) {
Ok(v) => { println!("{}", v); },
Err(err) => { println!("{}", err); }
}
}
public static double safe_div(int n, int d)
throws IllegalArgumentException {
if(d == 0)
throw new IllegalArgumentException("Divide by zero");
return n/d;
}
public static void main(String[] args) {
try {
System.out.println(safe_div(1, 0));
} catch(IllegalArgumentException err) {
System.err.println(err.getMessage());
}
C++ and Java both have exception throwing and handling capabilities, Rust does not. Instead Rust
handles errors through its return type, commonly using Result<T, E>
. The try-catch
is
replaced with a match on Ok
and Err
.
One should note that in Rust the f64
primitive type was used everywhere; whereas in C++ and Java
the respective compilers did not complain about the conversion from int
to double
. The Rust
compiler would not allow similar code to compile.