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:告訴編譯器「這段攔截是安全的」

匯入


  1. 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。
簽名:
  1. macro_rules! panic { ... }

注意:panic 發生後,panic! 之後的程式碼不會執行,但已建立的值仍會依序執行 Drop 清理。若專案設定 panic = "abort",則不會回溯展開,程式直接中止,下面介紹的 catch_unwind 也攔不到。
範例:
  1. struct Percent(u8);
  2. impl Percent {
  3. fn new(v: u8) -> Percent {
  4. if v > 100 {
  5. panic!("percent must be 0..=100, got {}", v);
  6. }
  7. Percent(v)
  8. }
  9. }
  10. fn main() {
  11. let ok = Percent::new(42);
  12. println!("ok = {}%", ok.0);
  13. let bad = Percent::new(150);
  14. println!("never printed: {}", bad.0);
  15. }

輸出:
  1. 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 換成空的掛鉤,避免預設訊息混入輸出。
簽名:
  1. 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 造成的中止。
範例:
  1. use std::panic;
  2. fn risky(n: i32) -> i32 {
  3. if n == 0 {
  4. panic!("zero is not allowed");
  5. }
  6. 100 / n
  7. }
  8. fn main() {
  9. panic::set_hook(Box::new(|_| {}));
  10. for n in [5, 0] {
  11. let result = panic::catch_unwind(|| risky(n));
  12. match result {
  13. Ok(v) => println!("n={} -> Ok({})", n, v),
  14. Err(payload) => {
  15. let msg = payload
  16. .downcast_ref::<&str>()
  17. .map(|s| s.to_string())
  18. .or_else(|| payload.downcast_ref::<String>().cloned())
  19. .unwrap_or_else(|| "unknown".to_string());
  20. println!("n={} -> panicked: {}", n, msg);
  21. }
  22. }
  23. }
  24. println!("main keeps running");
  25. }

輸出:
  1. n=5 -> Ok(20)
  2. n=0 -> panicked: zero is not allowed
  3. main keeps running

set_hook 與 take_hook:自訂 panic 訊息


panic 掛鉤(hook)是 panic 發生時、開始回溯展開之前被呼叫的函式。預設掛鉤會把訊息印到標準錯誤;用 set_hook 換成自己的版本,可以改變格式、寫入日誌檔或送出錯誤回報。take_hook 移除目前的掛鉤並把它回傳,同時恢復預設掛鉤。
掛鉤收到 &PanicHookInfo,提供 payload_as_str()(取得訊息字串,Rust 1.91 起)與 location()。
簽名:
  1. pub fn set_hook(hook: Box<dyn Fn(&PanicHookInfo<'_>) + Sync + Send + 'static>);
  2. pub fn take_hook() -> Box<dyn Fn(&PanicHookInfo<'_>) + Sync + Send + 'static>;

注意:掛鉤是整個程式共用的全域設定,任何執行緒 panic 都會呼叫它;在掛鉤裡再 panic 會讓程式直接中止。
範例:
  1. use std::panic;
  2. fn main() {
  3. panic::set_hook(Box::new(|info| {
  4. let msg = info.payload_as_str().unwrap_or("<non-string payload>");
  5. let place = info
  6. .location()
  7. .map(|l| format!("{}:{}", l.file(), l.line()))
  8. .unwrap_or_default();
  9. println!("[crash] {} (at {})", msg, place);
  10. }));
  11. let r = panic::catch_unwind(|| {
  12. let v: Vec<i32> = Vec::new();
  13. v[3]
  14. });
  15. println!("caught: {}", r.is_err());
  16. let r = panic::catch_unwind(|| {
  17. let n: Option<u8> = None;
  18. n.expect("config value missing")
  19. });
  20. println!("caught: {}", r.is_err());
  21. let _custom = panic::take_hook();
  22. println!("hook removed, default restored");
  23. }

輸出:
  1. [crash] index out of bounds: the len is 0 but the index is 3 (at main.rs:15)
  2. caught: true
  3. [crash] config value missing (at main.rs:21)
  4. caught: true
  5. 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 訊息會指向你的程式碼。
簽名:
  1. pub const fn caller() -> &'static Location<'static>;
  2. pub const fn file(&self) -> &'a str;
  3. pub const fn line(&self) -> u32;
  4. pub const fn column(&self) -> u32;

範例:
  1. use std::panic::{self, Location};
  2. #[track_caller]
  3. fn log_here(msg: &str) {
  4. let loc = Location::caller();
  5. println!("{}:{}:{} {}", loc.file(), loc.line(), loc.column(), msg);
  6. }
  7. #[track_caller]
  8. fn must_positive(n: i32) -> i32 {
  9. if n <= 0 {
  10. panic!("expected positive, got {}", n);
  11. }
  12. n
  13. }
  14. fn main() {
  15. log_here("first call");
  16. log_here("second call");
  17. panic::set_hook(Box::new(|info| {
  18. if let Some(loc) = info.location() {
  19. println!("panic reported at line {}", loc.line());
  20. }
  21. }));
  22. let r = panic::catch_unwind(|| must_positive(-1));
  23. println!("caught: {}", r.is_err());
  24. }

輸出:
  1. main.rs:18:5 first call
  2. main.rs:19:5 second call
  3. panic reported at line 26
  4. caught: true

AssertUnwindSafe:手動擔保展開安全


catch_unwind 要求閉包實作 UnwindSafe 特徵。捕獲 &mut 參考的閉包不符合,因為 panic 可能讓被修改到一半的資料處於不一致狀態,而攔截後你還會繼續使用它。
如果你確認攔截後的狀態可以接受(例如只是一份記錄),用 AssertUnwindSafe 包住閉包,向編譯器擔保這件事。範例中 log 停在 panic 發生前的狀態,第三步沒有加入。
簽名:
  1. pub struct AssertUnwindSafe<T>(pub T);

注意:AssertUnwindSafe 不會讓程式更安全,只是關閉編譯器的檢查;攔截後要自己確認資料仍然有效。
範例:
  1. use std::panic::{self, AssertUnwindSafe};
  2. fn main() {
  3. panic::set_hook(Box::new(|_| {}));
  4. let mut log: Vec<String> = Vec::new();
  5. let result = panic::catch_unwind(AssertUnwindSafe(|| {
  6. log.push("step 1".to_string());
  7. log.push("step 2".to_string());
  8. if log.len() == 2 {
  9. panic!("step 3 failed");
  10. }
  11. log.push("step 3".to_string());
  12. }));
  13. println!("panicked: {}", result.is_err());
  14. println!("log after panic: {:?}", log);
  15. }

輸出:
  1. panicked: true
  2. 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 位置就會指向呼叫者