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

โจทย์ทั้งหมด