Struct, Enum और Trait

Rust Error Handling: Result and ?

Errors are values in Rust. Return Result, handle it with match, and pass errors on with ?.

  • मध्यम
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • Ok and Err
  • The ? operator
  • Your own error messages
parse_and_double("abc")
  1. 1text.parse()fails
  2. 2?returns early
  3. 3Err(...)the caller gets the error

Success or error, as a value

Rust has no exceptions. A function that can fail returns Result<T, E>, which is either Ok(value) or Err(error). The caller decides what to do with the error.

The ? after parse returns the error to the caller at once when parsing fails; otherwise it gives the number. divide uses a String as its error type and returns Err for a zero divisor. match prints the value or the error message.

मुख्य बातें

  1. Result<T, E> is Ok(value) or Err(error).
  2. ? returns the error to the caller at once.
  3. The caller decides what to do.

चलने योग्य Rust उदाहरण

Rust
कोड चलाएँ →
main.rs
use std::num::ParseIntError;

fn parse_and_double(text: &str) -> Result<i32, ParseIntError> {
    let number: i32 = text.trim().parse()?; // ? returns the error early
    Ok(number * 2)
}

fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        return Err(String::from("cannot divide by zero"));
    }
    Ok(a / b)
}

fn main() {
    for input in ["21", "abc"] {
        match parse_and_double(input) {
            Ok(value) => println!("{input} -> {value}"),
            Err(error) => println!("{input} -> error: {error}"),
        }
    }

    println!("{:?}", divide(10, 2));
    println!("{:?}", divide(1, 0));
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
21 -> 42
abc -> error: invalid digit found in string
Ok(5)
Err("cannot divide by zero")

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

अगला: Bank Account with Result →

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज