CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
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}"),
        }
    }
}

Expected output

= 36
hata: sıfıra bölünemez
hata: geçersiz sayı: on

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>1.0 / 0.0</code> give with f64?

  • 0
  • A compile error
  • inf Correct answer
  • A panic

Explanation: Floating-point division follows IEEE 754 and gives infinity; that's why the divisor is checked separately. Dividing an integer by zero panics.

2 Propagate the error

Question
let a: f64 = p[0].parse().map_err(|_| "geçersiz".to_string())____;
Answer
let a: f64 = p[0].parse().map_err(|_| "geçersiz".to_string())?;

Explanation: ? returns the error to the caller if there is one; otherwise it gives the value.

3 Input and result

Term Meaning
"12 * 3" = 36
"12 / 0" division-by-zero error
"on * 3" invalid number: on
"12 *" format error

All lessons in Beginner