AnyCompiler

Error Handling

? operator, Result propagate karne ka shorthand hai: agar expression Err hai, to ? turant current function se us error ko return kar deta hai; agar Ok hai, to ? value ko unwrap kar deta hai aur execution continue hota hai. Neeche s.parse()? aapko ya to ek valid i32 deta hai ya parse error ke sath parse_and_double se jaldi exit ho jaata hai.

use std::num::ParseIntError;

fn parse_and_double(s: &str) -> Result<i32, ParseIntError> {
    let n: i32 = s.parse()?;
    Ok(n * 2)
}

fn main() {
    match parse_and_double("21") {
        Ok(n) => println!("Doubled: {}", n),
        Err(e) => println!("Error: {}", e),
    }

    match parse_and_double("not a number") {
        Ok(n) => println!("Doubled: {}", n),
        Err(e) => println!("Error: {}", e),
    }
}
Output
Doubled: 42
Error: invalid digit found in string

Ek custom error type

Apne khud ke functions ke liye, ek custom error type — chahe NegativeNumberError jitna simple ho — ek generic error reuse karne se aksar zyada clear hota hai. Iske liye Display trait implement karna hi hai jo {} ko println! ke andar directly isko format karne deta hai.

use std::fmt;

#[derive(Debug)]
struct NegativeNumberError;

impl fmt::Display for NegativeNumberError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "number must not be negative")
    }
}

fn square_root_ish(n: i32) -> Result<f64, NegativeNumberError> {
    if n < 0 {
        return Err(NegativeNumberError);
    }
    Ok((n as f64).sqrt())
}

fn main() {
    match square_root_ish(16) {
        Ok(result) => println!("Result: {}", result),
        Err(e) => println!("Error: {}", e),
    }

    match square_root_ish(-4) {
        Ok(result) => println!("Result: {}", result),
        Err(e) => println!("Error: {}", e),
    }
}
Output
Result: 4
Error: number must not be negative

Aage: collections aur standard library — HashMap, aur ek closing look ki Rust ki standard library aur kya provide karti hai.

Practice Exercise

Ek function safe_divide(a: f64, b: f64) -> Result<f64, String> likho jo Err("cannot divide by zero".to_string()) return kare agar b 0.0 ho, warna Ok(a / b). Use (10.0, 0.0) ke sath call karo, result ko match karo, aur agar Err ho to error message print karo.