Skip to content

Day 13 - 错误处理

panic!

rust
panic!("something wrong");

// 处理panic
std::panic::catch_unwind(|| {
    // 可能panic的代码
});

? 运算符

rust
fn read_file(path: &str) -> Result<String, io::Error> {
    let mut file = File::open(path)?;
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    Ok(content)
}

自定义错误

rust
use std::fmt;

#[derive(Debug)]
struct MyError(String);

impl fmt::Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::error::Error for MyError {}

📅 学习进度

Day主题状态
01-12基础
13错误处理
14智能指针

本文为Rust 30天学习计划第13天内容

📚 导航

| ← Day 12 - 上一章 | Day 14 - 下一章 →

最后更新: