std::panic
最後更新
控制 panic 的行為:攔截 panic、自訂 panic 時印出的訊息、查詢 panic 發生的位置。
這個模組做什麼
panic 是 Rust 對「不該發生的錯誤」的反應:程式印出錯誤訊息,沿著呼叫堆疊一路往回清理(稱為 unwinding,回溯展開),最後結束那條執行緒。主執行緒 panic 時,整個程式以結束碼 101 結束。
什麼時候該 panic、什麼時候該回傳
Result?| 情況 | 做法 |
|---|---|
| 呼叫者可能預期、能處理的失敗(檔案不存在、輸入格式錯) | 回傳 Result(見 std::result) |
| 程式邏輯錯誤、違反不變條件(索引越界、不可能的狀態) | panic! |
| 範例、測試、原型 | unwrap/expect 可以接受 |
std::panic 模組本身不負責「引發」panic(那是 panic! 巨集),而是提供周邊工具:catch_unwind:攔截 panic,讓程式繼續跑set_hook/take_hook:自訂 panic 時要做什麼Location:取得原始碼的檔名、行號、欄號AssertUnwindSafe:告訴編譯器「這段攔截是安全的」
匯入
- use std::panic::{self, AssertUnwindSafe, Location};
panic! 巨集在 prelude 中,不需要匯入。常用 API
panic!:遇到不可能的狀態時中止
panic! 接受和 format! 相同的格式字串。它不會返回,型別是 !,所以可以放在任何需要值的地方。unwrap、expect、assert!、陣列索引越界、整數除以零,底層都是 panic。下面的範例在
Percent::new 收到不合法的值時 panic。輸出區塊只列出標準輸出;標準錯誤會印出 thread 'main' (<執行緒 ID>) panicked at main.rs:6:13:,下一行是 percent must be 0..=100, got 150,接著提示可設定 RUST_BACKTRACE=1(見 std::backtrace)。程式結束碼為 101。簽名:
- macro_rules! panic { ... }
注意:panic 發生後,
panic! 之後的程式碼不會執行,但已建立的值仍會依序執行 Drop 清理。若專案設定 panic = "abort",則不會回溯展開,程式直接中止,下面介紹的 catch_unwind 也攔不到。範例:
- struct Percent(u8);
- impl Percent {
- fn new(v: u8) -> Percent {
- if v > 100 {
- panic!("percent must be 0..=100, got {}", v);
- }
- Percent(v)
- }
- }
- fn main() {
- let ok = Percent::new(42);
- println!("ok = {}%", ok.0);
- let bad = Percent::new(150);
- println!("never printed: {}", bad.0);
- }
輸出:
- ok = 42%
catch_unwind:攔截 panic
catch_unwind 執行一個閉包(closure):正常結束得到 Ok(回傳值),panic 則得到 Err(payload)。payload 是 Box<dyn Any + Send>,通常是 &'static str(固定字串)或 String(有格式化參數),要用 downcast_ref 取出(見 std::any)。適用情境:外掛或使用者提供的程式碼不能拖垮主程式、在 FFI 邊界阻止 panic 跨到 C。範例開頭用
set_hook 換成空的掛鉤,避免預設訊息混入輸出。簽名:
- pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R, Box<dyn Any + Send + 'static>>;
注意:
catch_unwind 不是 try/catch,不要拿來做一般的錯誤處理;預期會發生的錯誤應該用 Result。它也攔不到 abort 模式下的 panic,以及 panic 處理過程中再次 panic 造成的中止。範例:
- use std::panic;
- fn risky(n: i32) -> i32 {
- if n == 0 {
- panic!("zero is not allowed");
- }
- 100 / n
- }
- fn main() {
- panic::set_hook(Box::new(|_| {}));
- for n in [5, 0] {
- let result = panic::catch_unwind(|| risky(n));
- match result {
- Ok(v) => println!("n={} -> Ok({})", n, v),
- Err(payload) => {
- let msg = payload
- .downcast_ref::<&str>()
- .map(|s| s.to_string())
- .or_else(|| payload.downcast_ref::<String>().cloned())
- .unwrap_or_else(|| "unknown".to_string());
- println!("n={} -> panicked: {}", n, msg);
- }
- }
- }
- println!("main keeps running");
- }
輸出:
- n=5 -> Ok(20)
- n=0 -> panicked: zero is not allowed
- main keeps running
set_hook 與 take_hook:自訂 panic 訊息
panic 掛鉤(hook)是 panic 發生時、開始回溯展開之前被呼叫的函式。預設掛鉤會把訊息印到標準錯誤;用
set_hook 換成自己的版本,可以改變格式、寫入日誌檔或送出錯誤回報。take_hook 移除目前的掛鉤並把它回傳,同時恢復預設掛鉤。掛鉤收到
&PanicHookInfo,提供 payload_as_str()(取得訊息字串,Rust 1.91 起)與 location()。簽名:
- pub fn set_hook(hook: Box<dyn Fn(&PanicHookInfo<'_>) + Sync + Send + 'static>);
- pub fn take_hook() -> Box<dyn Fn(&PanicHookInfo<'_>) + Sync + Send + 'static>;
注意:掛鉤是整個程式共用的全域設定,任何執行緒 panic 都會呼叫它;在掛鉤裡再 panic 會讓程式直接中止。
範例:
- use std::panic;
- fn main() {
- panic::set_hook(Box::new(|info| {
- let msg = info.payload_as_str().unwrap_or("<non-string payload>");
- let place = info
- .location()
- .map(|l| format!("{}:{}", l.file(), l.line()))
- .unwrap_or_default();
- println!("[crash] {} (at {})", msg, place);
- }));
- let r = panic::catch_unwind(|| {
- let v: Vec<i32> = Vec::new();
- v[3]
- });
- println!("caught: {}", r.is_err());
- let r = panic::catch_unwind(|| {
- let n: Option<u8> = None;
- n.expect("config value missing")
- });
- println!("caught: {}", r.is_err());
- let _custom = panic::take_hook();
- println!("hook removed, default restored");
- }
輸出:
- [crash] index out of bounds: the len is 0 but the index is 3 (at main.rs:15)
- caught: true
- [crash] config value missing (at main.rs:21)
- caught: true
- hook removed, default restored
Location 與 #[track_caller]:發生在哪一行
Location 記錄原始碼位置:file()、line()、column()。Location::caller() 回傳「呼叫目前函式的位置」,但只有函式標上 #[track_caller] 屬性時才會往外追一層,否則就是 caller() 這行本身。#[track_caller] 也會影響 panic 訊息的位置:範例中 must_positive 標了這個屬性,所以 panic 回報的是 main 裡呼叫它的那一行,而不是 panic! 所在的那一行。Option::unwrap 就是這樣做的,所以 panic 訊息會指向你的程式碼。簽名:
- pub const fn caller() -> &'static Location<'static>;
- pub const fn file(&self) -> &'a str;
- pub const fn line(&self) -> u32;
- pub const fn column(&self) -> u32;
範例:
- use std::panic::{self, Location};
- #[track_caller]
- fn log_here(msg: &str) {
- let loc = Location::caller();
- println!("{}:{}:{} {}", loc.file(), loc.line(), loc.column(), msg);
- }
- #[track_caller]
- fn must_positive(n: i32) -> i32 {
- if n <= 0 {
- panic!("expected positive, got {}", n);
- }
- n
- }
- fn main() {
- log_here("first call");
- log_here("second call");
- panic::set_hook(Box::new(|info| {
- if let Some(loc) = info.location() {
- println!("panic reported at line {}", loc.line());
- }
- }));
- let r = panic::catch_unwind(|| must_positive(-1));
- println!("caught: {}", r.is_err());
- }
輸出:
- main.rs:18:5 first call
- main.rs:19:5 second call
- panic reported at line 26
- caught: true
AssertUnwindSafe:手動擔保展開安全
catch_unwind 要求閉包實作 UnwindSafe 特徵。捕獲 &mut 參考的閉包不符合,因為 panic 可能讓被修改到一半的資料處於不一致狀態,而攔截後你還會繼續使用它。如果你確認攔截後的狀態可以接受(例如只是一份記錄),用
AssertUnwindSafe 包住閉包,向編譯器擔保這件事。範例中 log 停在 panic 發生前的狀態,第三步沒有加入。簽名:
- pub struct AssertUnwindSafe<T>(pub T);
注意:
AssertUnwindSafe 不會讓程式更安全,只是關閉編譯器的檢查;攔截後要自己確認資料仍然有效。範例:
- use std::panic::{self, AssertUnwindSafe};
- fn main() {
- panic::set_hook(Box::new(|_| {}));
- let mut log: Vec<String> = Vec::new();
- let result = panic::catch_unwind(AssertUnwindSafe(|| {
- log.push("step 1".to_string());
- log.push("step 2".to_string());
- if log.len() == 2 {
- panic!("step 3 failed");
- }
- log.push("step 3".to_string());
- }));
- println!("panicked: {}", result.is_err());
- println!("log after panic: {:?}", log);
- }
輸出:
- panicked: true
- log after panic: ["step 1", "step 2"]
重點整理
- 可預期的失敗回傳
Result;違反不變條件、不該發生的狀況才panic! - 主執行緒 panic 讓程式以結束碼 101 結束;
Drop仍會在回溯展開時執行 catch_unwind攔截 panic,payload 用downcast_ref::<&str>()或::<String>()取出set_hook自訂 panic 訊息,是全域設定- 輔助函式加上
#[track_caller],panic 位置就會指向呼叫者