21. panic 与 Result

  • 区分不可恢复错误与可恢复错误。
  • 使用 panic! 处理不可恢复错误。
  • 使用 Result<T, E> 处理可恢复错误。
  • 使用 ? 运算符传播错误。

Rust 把错误分为两类:

  • 不可恢复错误:程序 bug 或严重问题,通常应该终止程序。
  • 可恢复错误:例如文件不存在、网络失败,可以通知调用者处理。

对应机制:

  • panic!:不可恢复错误。
  • Result<T, E>:可恢复错误。
snippet.rust
fn main() {
    panic!("crash and burn");
}

程序会立即终止,并打印回溯信息(backtrace)。

运行程序时设置环境变量:

snippet.bash
RUST_BACKTRACE=1 cargo run

可以看到 panic 发生的位置调用栈。

`panic!` 适合程序进入无法继续的状态,例如内部逻辑不一致。

## 21.4 Result<T, E>

对于可能失败的操作,Rust 返回 Result:

snippet.rust
enum Result<T, E> {
    Ok(T),
    Err(E),
}

示例:打开文件

snippet.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);
        }
    };
}
snippet.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)
            }
        },
    };
}

如果确定操作不会失败,可以用 unwrap:

snippet.rust
let f = File::open("hello.txt").unwrap();

或者提供自定义错误信息:

snippet.rust
let f = File::open("hello.txt").expect("hello.txt should be included in this project");
生产代码中应谨慎使用 `unwrap`,建议用 `?` 或 `match` 处理错误。

## 21.7 ? 运算符

? 用于简化 Result 的错误传播:

snippet.rust
use std::fs::File;
use std::io::{self, Read};
 
fn read_username_from_file() -> Result<String, io::Error> {
    let mut f = File::open("hello.txt")?;
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    Ok(s)
}

如果 File::open 返回 Err,函数会立即返回这个 Err;否则继续执行。

? 也可以用于 Option:

snippet.rust
fn last_char_of_first_line(text: &str) -> Option<char> {
    text.lines().next()?.chars().last()
}

从 Rust 1.26 起,main 也可以返回 Result:

snippet.rust
use std::fs::File;
 
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let f = File::open("hello.txt")?;
    Ok(())
}
情况 机制 示例
不可恢复错误 panic! 内部 bug
可恢复错误 Result<T, E> 文件不存在
确定不会失败 unwrap / expect 快速原型
传播错误 ? 函数返回 Result
  1. 什么时候应该使用 panic!,什么时候应该使用 Result?
  2. unwrap 和 expect 有什么区别?
  3. 用 ? 运算符改写一段使用 match 处理 Result 的代码。

该主题尚不存在

您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。

  • rust/panic_与_result.txt
  • 最后更改: 2026/08/12 23:35
  • 由 张叶安