পাঠ ৯.১

panic! দিয়ে unrecoverable error

Unrecoverable Errors with panic!

Rust-এ error দু'রকম —

  • RecoverableResult<T, E> (যেমন file না পাওয়া)। পরের পাঠে।
  • Unrecoverablepanic! macro (যেমন array-এর সীমার বাইরে index)। এই পাঠ।

panic! কী করে?

Default-এ panic হলে program — (১) message print করে, (২) stack unwind করে memory cleanup করে, (৩) quit করে।

Unwind বনাম abort

Unwind cleanup করে — কিন্তু extra code দরকার, binary বড় হয়। Cleanup চাও না, immediate exit চাও — release build-এ Cargo.toml-এ:

Cargo.tomltoml
[profile.release]
panic = 'abort'

Binary ছোট হয়, কিন্তু OS-কে cleanup-এর দায়িত্ব দিতে হয়।

Explicit panic!

src/main.rsrust
fn main() {
    panic!("crash and burn");
}
terminal outputtext
thread 'main' panicked at src/main.rs:2:5:
crash and burn
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

File location src/main.rs:2:5 — line 2, column 5।

Accidental panic — out-of-bounds

src/main.rsrust
fn main() {
    let v = vec![1, 2, 3];

    v[99];
}
terminal outputtext
thread 'main' panicked at src/main.rs:4:6:
index out of bounds: the len is 3 but the index is 99

C/C++-এ এটা undefined behavior — ঐ memory-তে যা কিছু আছে সেটা return হত। Buffer overread vulnerability — attacker সেই memory-র ভিতরে অন্য data (password, key) read করতে পারে।

Rust এই attack vector পুরোপুরি বন্ধ করে দিয়েছে — invalid index দিলে program সাথে সাথে stop, কোনো garbage memory expose হয় না।

Backtrace দেখা

Panic কোথা থেকে এসেছে — পুরো call chain দেখতে RUST_BACKTRACE=1 environment variable:

terminalbash
$ RUST_BACKTRACE=1 cargo run
thread 'main' panicked at src/main.rs:4:6:
index out of bounds: the len is 3 but the index is 99
stack backtrace:
   0: rust_begin_unwind
   1: core::panicking::panic_fmt
   2: core::panicking::panic_bounds_check
   3: <usize as core::slice::index::SliceIndex<[T]>>::index
   ...
   6: panic::main
             at ./src/main.rs:4:6
   ...

কীভাবে পড়বে —

  • উপর থেকে নিচের দিকে যাও।
  • প্রথম যে line তোমার লেখা file-এ — সেটাই panic-এর origin (এখানে line 6, panic::main at ./src/main.rs:4:6)।
  • উপরের code তোমার code যা call করেছে।
  • নিচের code যা তোমার code-কে call করেছে।

Backtrace পেতে debug symbol দরকার — cargo run (release ছাড়া) default-এই দেয়।

এই পাঠ থেকে যা শিখলে

  • Two error categories — Result (recoverable), panic! (unrecoverable)।
  • Default — unwind + cleanup + quit। Release-এ panic = 'abort' set করলে immediate exit।
  • Panic আসে — explicit panic!() call থেকে, বা invalid action (out-of-bounds, etc.) থেকে।
  • RUST_BACKTRACE=1 দিয়ে call chain দেখো — তোমার লেখা file-এর প্রথম line-ই origin।