# 21. panic 与 Result ## 学习目标 - 区分不可恢复错误与可恢复错误。 - 使用 `panic!` 处理不可恢复错误。 - 使用 `Result` 处理可恢复错误。 - 使用 `?` 运算符传播错误。 ## 21.1 两类错误 Rust 把错误分为两类: - **不可恢复错误**:程序 bug 或严重问题,通常应该终止程序。 - **可恢复错误**:例如文件不存在、网络失败,可以通知调用者处理。 对应机制: - `panic!`:不可恢复错误。 - `Result`:可恢复错误。 ## 21.2 `panic!` ```rust fn main() { panic!("crash and burn"); } ``` 程序会立即终止,并打印回溯信息(backtrace)。 ## 21.3 查看 backtrace 运行程序时设置环境变量: ```bash RUST_BACKTRACE=1 cargo run ``` 可以看到 panic 发生的位置调用栈。 > `panic!` 适合程序进入无法继续的状态,例如内部逻辑不一致。 ## 21.4 `Result` 对于可能失败的操作,Rust 返回 `Result`: ```rust enum Result { Ok(T), Err(E), } ``` 示例:打开文件 ```rust use std::fs::File; fn main() { let f = File::open("hello.txt"); let f = match f { Ok(file) => file, Err(error) => { panic!("Problem opening the file: {:?}", error); } }; } ``` ## 21.5 匹配不同错误 ```rust use std::fs::File; use std::io::ErrorKind; fn main() { let f = File::open("hello.txt"); let f = match f { Ok(file) => file, Err(error) => match error.kind() { ErrorKind::NotFound => match File::create("hello.txt") { Ok(fc) => fc, Err(e) => panic!("Problem creating the file: {:?}", e), }, other_error => { panic!("Problem opening the file: {:?}", other_error) } }, }; } ``` ## 21.6 `unwrap` 和 `expect` 如果确定操作不会失败,可以用 `unwrap`: ```rust let f = File::open("hello.txt").unwrap(); ``` 或者提供自定义错误信息: ```rust let f = File::open("hello.txt").expect("hello.txt should be included in this project"); ``` > 生产代码中应谨慎使用 `unwrap`,建议用 `?` 或 `match` 处理错误。 ## 21.7 `?` 运算符 `?` 用于简化 `Result` 的错误传播: ```rust use std::fs::File; use std::io::{self, Read}; fn read_username_from_file() -> Result { let mut f = File::open("hello.txt")?; let mut s = String::new(); f.read_to_string(&mut s)?; Ok(s) } ``` 如果 `File::open` 返回 `Err`,函数会立即返回这个 `Err`;否则继续执行。 ## 21.8 `?` 与 `Option` `?` 也可以用于 `Option`: ```rust fn last_char_of_first_line(text: &str) -> Option { text.lines().next()?.chars().last() } ``` ## 21.9 `main` 函数返回 `Result` 从 Rust 1.26 起,`main` 也可以返回 `Result`: ```rust use std::fs::File; fn main() -> Result<(), Box> { let f = File::open("hello.txt")?; Ok(()) } ``` ## 21.10 小结 | 情况 | 机制 | 示例 | | 不可恢复错误 | `panic!` | 内部 bug | | 可恢复错误 | `Result` | 文件不存在 | | 确定不会失败 | `unwrap` / `expect` | 快速原型 | | 传播错误 | `?` | 函数返回 `Result` | ## 21.11 思考题 1. 什么时候应该使用 `panic!`,什么时候应该使用 `Result`? 2. `unwrap` 和 `expect` 有什么区别? 3. 用 `?` 运算符改写一段使用 `match` 处理 `Result` 的代码。