panic 展开与终止 ​

核心概念 ​

当 panic! 被触发后,Rust 提供了两种处理策略:展开(Unwind)和终止(Abort)。展开是默认行为,程序会从 panic 发生的地方开始,沿着调用栈逐层向上回溯,在每一层调用已创建值的析构函数(Drop),确保所有资源被正确释放,然后线程退出。终止模式则直接让进程立即退出,不执行任何析构函数,由操作系统回收所有资源。

rust
struct Guard {
    name: String,
}

impl Guard {
    fn new(name: &str) -> Self {
        println!("[{}] 创建", name);
        Guard { name: name.to_string() }
    }
}

impl Drop for Guard {
    fn drop(&mut self) {
        // 展开模式下,panic 后仍会执行 drop
        println!("[{}] 释放资源", self.name);
    }
}

fn inner() {
    let _g3 = Guard::new("内层资源");
    panic!("内层 panic");
    // _g3 的 Drop 会被调用
}

fn middle() {
    let _g2 = Guard::new("中层资源");
    inner();
    // _g2 的 Drop 会被调用
}

fn outer() {
    let _g1 = Guard::new("外层资源");
    middle();
    // _g1 的 Drop 会被调用
}

fn main() {
    // 展开模式下的输出顺序:
    // [外层资源] 创建
    // [中层资源] 创建
    // [内层资源] 创建
    // thread 'main' panicked at '内层 panic'
    // [内层资源] 释放资源   ← 逆序释放
    // [中层资源] 释放资源
    // [外层资源] 释放资源

    // outer();  // 取消注释运行
    println!("演示展开流程(取消注释 outer() 查看)");
}

展开模式(Unwind) ​

展开是默认的 panic 策略。它保证所有已创建的值都会被正确析构。

rust
use std::fs::File;
use std::io::Write;

struct TempFile {
    path: String,
}

impl TempFile {
    fn new(path: &str) -> Self {
        // 创建临时文件
        let mut file = File::create(path).expect("无法创建文件");
        file.write_all(b"临时数据").expect("写入失败");
        println!("创建临时文件: {}", path);
        TempFile { path: path.to_string() }
    }
}

impl Drop for TempFile {
    fn drop(&mut self) {
        // 展开时会执行:清理临时文件
        if std::path::Path::new(&self.path).exists() {
            std::fs::remove_file(&self.path).ok();
            println!("删除临时文件: {}", self.path);
        }
    }
}

fn process_data() {
    let _tmp = TempFile::new("temp_data.txt");
    // 即使 panic,临时文件也会被清理(展开模式下)
    // panic!("处理失败");
    println!("处理完成");
}

fn main() {
    process_data();
    // 文件会在 _tmp 离开作用域时删除
}

终止模式(Abort) ​

在 Cargo.toml 中设置 panic = 'abort' 可以切换为终止模式。

toml
# Cargo.toml 配置
[profile.dev]
panic = "unwind"    # 开发模式默认展开

[profile.release]
panic = "abort"     # 发布模式可以设为终止
特性展开(Unwind)终止(Abort)
析构函数执行不执行
资源清理Rust 管理操作系统回收
catch_unwind可以捕获不能捕获
二进制大小较大(包含展开表)较小
panic 速度较慢(逐层析构)快(直接退出)
适用场景通用程序、服务端嵌入式、小二进制
rust
// 展开模式下可以捕获 panic
use std::panic;

fn risky_operation() {
    panic!("出了问题");
}

fn main() {
    // catch_unwind:捕获 panic,防止线程崩溃
    // 仅在展开模式下有效
    let result = panic::catch_unwind(|| {
        risky_operation();
    });

    match result {
        Ok(()) => println!("操作成功"),
        Err(e) => {
            // 获取 panic 信息
            if let Some(msg) = e.downcast_ref::<&str>() {
                println!("捕获到 panic: {}", msg);
            } else if let Some(msg) = e.downcast_ref::<String>() {
                println!("捕获到 panic: {}", msg);
            } else {
                println!("捕获到未知类型的 panic");
            }
        }
    }

    println!("程序继续运行");
}

catch_unwind 的使用场景 ​

catch_unwind 不是用来实现异常处理的。它的正当用途很少,主要包括:

rust
use std::panic;

// 场景1:服务器处理请求,一个请求 panic 不应该影响整个服务
fn handle_request(request_id: u32) {
    let result = panic::catch_unwind(|| {
        // 模拟处理请求
        if request_id == 3 {
            panic!("请求 {} 处理失败", request_id);
        }
        println!("请求 {} 处理成功", request_id);
    });

    if let Err(_) = result {
        println!("请求 {} 出错,已隔离", request_id);
    }
}

// 场景2:FFI 边界,防止 panic 跨越 FFI 传播(未定义行为)
// extern "C" fn callback() {
//     let result = panic::catch_unwind(|| {
//         // 可能 panic 的 Rust 代码
//     });
//     if result.is_err() {
//         // 返回错误码给 C 代码
//     }
// }

fn main() {
    println!("=== 服务器模拟 ===");
    for id in 1..=5 {
        handle_request(id);
    }
    println!("服务器仍在运行");
}

panic hook 简介 ​

可以通过 std::panic::set_hook 自定义 panic 时的行为,比如记录日志或发送错误报告。

rust
use std::panic;

fn main() {
    // 设置自定义 panic hook
    panic::set_hook(Box::new(|info| {
        // info 包含 panic 的位置和消息
        let location = info.location()
            .map(|l| format!("{}:{}:{}", l.file(), l.line(), l.column()))
            .unwrap_or_else(|| String::from("未知位置"));

        let message = if let Some(s) = info.payload().downcast_ref::<&str>() {
            s.to_string()
        } else if let Some(s) = info.payload().downcast_ref::<String>() {
            s.clone()
        } else {
            String::from("未知错误")
        };

        eprintln!("[自定义 PANIC] 位置: {}", location);
        eprintln!("[自定义 PANIC] 消息: {}", message);
        // 实际项目中可以在这里写日志、发送报警等
    }));

    // 触发 panic 会使用自定义 hook
    let result = panic::catch_unwind(|| {
        panic!("测试自定义 hook");
    });

    if result.is_err() {
        println!("panic 已被捕获并通过自定义 hook 处理");
    }
}

基本示例 ​

展示展开和终止模式下的资源管理差异:

rust
use std::panic;

// 模拟数据库连接
struct DbConnection {
    id: u32,
    active: bool,
}

impl DbConnection {
    fn new(id: u32) -> Self {
        println!("  [DB#{}] 连接建立", id);
        DbConnection { id, active: true }
    }

    fn query(&self, sql: &str) -> Result<Vec<String>, String> {
        if !self.active {
            return Err(String::from("连接已关闭"));
        }
        if sql.contains("DROP") {
            panic!("危险操作!试图执行 DROP 语句");
        }
        println!("  [DB#{}] 执行: {}", self.id, sql);
        Ok(vec![String::from("结果行1"), String::from("结果行2")])
    }
}

impl Drop for DbConnection {
    fn drop(&mut self) {
        self.active = false;
        println!("  [DB#{}] 连接已关闭(资源释放)", self.id);
    }
}

// 模拟文件锁
struct FileLock {
    path: String,
}

impl FileLock {
    fn acquire(path: &str) -> Self {
        println!("  [锁] 获取文件锁: {}", path);
        FileLock { path: path.to_string() }
    }
}

impl Drop for FileLock {
    fn drop(&mut self) {
        println!("  [锁] 释放文件锁: {}", self.path);
    }
}

fn safe_operation() {
    println!("\n--- 安全操作 ---");
    let conn = DbConnection::new(1);
    let _lock = FileLock::acquire("data.db");

    match conn.query("SELECT * FROM users") {
        Ok(rows) => println!("  查询到 {} 行", rows.len()),
        Err(e) => println!("  查询失败: {}", e),
    }
    // conn 和 _lock 在作用域结束时正常释放
}

fn dangerous_operation() {
    println!("\n--- 危险操作(展开模式下 panic 但资源仍被释放) ---");
    let _conn = DbConnection::new(2);
    let _lock = FileLock::acquire("data.db");

    // 这会 panic,但展开模式下 _conn 和 _lock 的 Drop 仍会执行
    // _conn.query("DROP TABLE users");
    println!("  (取消注释 DROP 语句查看 panic 展开行为)");
}

fn guarded_operation() {
    println!("\n--- 受保护操作(catch_unwind) ---");
    let result = panic::catch_unwind(|| {
        let conn = DbConnection::new(3);
        let _lock = FileLock::acquire("important.db");
        // 即使 panic,catch_unwind 内的资源也会被展开释放
        conn.query("SELECT 1").unwrap();
        println!("  操作成功");
    });

    match result {
        Ok(()) => println!("  受保护操作完成"),
        Err(_) => println!("  受保护操作 panic,已恢复"),
    }
}

fn main() {
    safe_operation();
    dangerous_operation();
    guarded_operation();

    println!("\n程序正常结束");
}

常见问题 ​

问题一:什么时候选择 abort 模式?

当你不需要 catch_unwind、不需要 panic 时执行析构函数,或者需要减小二进制体积(如嵌入式、WebAssembly)时选择 abort。大多数通用程序使用默认的 unwind 模式。

问题二:catch_unwind 能捕获所有 panic 吗?

在 unwind 模式下可以捕获 panic! 宏和标准库的 panic。但不能捕获 abort 模式下的 panic,也不能捕获栈溢出等系统级错误。另外,如果闭包内部的类型不是 UnwindSafe 的,需要用 AssertUnwindSafe 包装。

问题三:展开过程中的 panic(double panic)会怎样?

如果在析构函数(Drop::drop)中再次 panic(即展开过程中再次 panic),程序会立即终止(abort),因为双重 panic 无法安全处理。

问题四:panic 和 abort 对性能有影响吗?

展开模式会在二进制文件中包含展开表(unwind tables),增加约 10-20% 的体积。运行时性能没有影响(展开表只在 panic 发生时使用)。abort 模式可以让编译器进行更多优化,同时生成更小的二进制。

适用场景 ​

  • 展开模式:通用程序、服务端程序、需要资源清理的场景
  • 终止模式:嵌入式系统、WebAssembly、追求小体积的场景
  • catch_unwind:服务器隔离请求失败、FFI 边界防护

注意事项 ​

  • 默认 panic 策略是展开(unwind)
  • 展开会逐层调用 Drop,保证资源释放
  • 终止模式(abort)不执行析构函数,直接退出进程
  • catch_unwind 只在展开模式下有效
  • catch_unwind 不是异常处理机制,使用场景很少
  • Drop 中再次 panic 会导致程序直接终止
  • abort 模式生成更小的二进制,展开模式更安全
  • 通过 Cargo.toml 的 [profile.xxx] 中 panic 字段配置

总结 ​

Rust 的 panic 有两种处理策略:展开和终止。展开是默认模式,panic 后沿调用栈逐层执行析构函数释放资源,可以被 catch_unwind 捕获;终止模式直接退出进程,不执行析构函数,生成更小的二进制。通过 Cargo.toml 的 panic = "unwind" 或 panic = "abort" 配置。catch_unwind 的正当用途有限,主要用于服务器隔离请求失败和 FFI 边界防护。展开过程中的二次 panic 会导致进程立即终止。大多数程序使用默认的展开模式,嵌入式和追求小体积的场景可以选择终止模式。