Rust
Error handling
Handle parse errors with Result and warn the user.
Handling errors
The user might type 12 / 0 or on * 3. To report each error with a clear message, a function that processes the whole line is chained with ?:
fn isle(satir: &str) -> Result<f64, String> {
let p: Vec<&str> = satir.split_whitespace().collect();
if p.len() != 3 {
return Err("biçim: SAYI İŞLEM SAYI".to_string());
}
let a: f64 = p[0].parse().map_err(|_| format!("geçersiz sayı: {}", p[0]))?;
let b: f64 = p[2].parse().map_err(|_| format!("geçersiz sayı: {}", p[2]))?;
if p[1] == "/" && b == 0.0 {
return Err("sıfıra bölünemez".to_string());
}
hesapla(a, p[1], b)
}
Handling the result
On the main side, match prints both success and error; the program doesn't crash because of an error:
match isle("12 / 0") {
Ok(s) => println!("= {s}"),
Err(e) => println!("hata: {e}"),
}
Explicit handling like this is preferred over unwrap in user-facing programs.
Exercise Process the line
Write the isle function above (and a simple hesapla). For the inputs ["12 * 3", "12 / 0", "on * 3"], print = result or hata: message with match.
Show example solution
fn hesapla(a: f64, op: &str, b: f64) -> Result<f64, String> {
match op {
"+" => Ok(a + b),
"-" => Ok(a - b),
"*" => Ok(a * b),
"/" => Ok(a / b),
_ => Err(format!("bilinmeyen işlem: {op}")),
}
}
fn isle(line: &str) -> Result<f64, String> {
let p: Vec<&str> = line.split_whitespace().collect();
if p.len() != 3 {
return Err("biçim: SAYI İŞLEM SAYI".to_string());
}
let a: f64 = p[0].parse().map_err(|_| format!("geçersiz sayı: {}", p[0]))?;
let b: f64 = p[2].parse().map_err(|_| format!("geçersiz sayı: {}", p[2]))?;
if p[1] == "/" && b == 0.0 {
return Err("sıfıra bölünemez".to_string());
}
hesapla(a, p[1], b)
}
fn main() {
for girdi in ["12 * 3", "12 / 0", "on * 3"] {
match isle(girdi) {
Ok(s) => println!("= {s}"),
Err(e) => println!("hata: {e}"),
}
}
}
Test yourself
-
What does <code>1.0 / 0.0</code> give with f64?
- 0
- A compile error
- inf
- A panic
Show answer
inf — Floating-point division follows IEEE 754 and gives infinity; that's why the divisor is checked separately. Dividing an integer by zero panics.
-
Propagate the error
let a: f64 = p[0].parse().map_err(|_| "geçersiz".to_string())____;
Show answer
let a: f64 = p[0].parse().map_err(|_| "geçersiz".to_string())?;
-
Input and result
- "12 * 3"
- = 36
- "12 / 0"
- division-by-zero error
- "on * 3"
- invalid number: on
- "12 *"
- format error
Next lesson: Loop and exit