[Rust] About Panic

고승우·2024년 7월 15일
0

Rust

목록 보기
10/16
post-thumbnail

Panic

Panic is a kind of error that should never happend. Rust can either unwind the stack when a panic happens or abort the process. Unwinding is the default. Panic proceed as follows

  1. Print error message: If you set the RUST_BACKTRACE environment variable, as the messages suggests, Rust will also dump the stack at this point.
  2. Unwind stack: Any temporary values, local variables, or arguments that the current function was using are dropped, in the reverse of the order they were created. Then move to that function’s caller, and so on up the stack.
  3. Exit thread: If the panicking thread was the main thread, then the whole process exits.

Aborting

There are two circumstances in which Rust does not try to unwind the stack.

  1. .drop() method triggers a second panic while Rust is still trying to clean up after the first:
struct PanicOnDrop;

impl Drop for PanicOnDrop {
    fn drop(&mut self) {
        println!("Dropping!");
        panic!("Panic in Drop!");
    }
}

fn main() {
    let _x = PanicOnDrop;

    // This will cause a panic
    panic!("Main panic!");
}
  1. Customize panic behavior: If you compile with -C panic=abort, the first panic in your program immediately aborts the process. (With this option, Rust does not need to know how to unwind the stack, so this can reduce the size of your compiled code.)
profile
٩( ᐛ )و 

0개의 댓글