Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

panic!

panic! 매크로는 패닉을 생성하고 스택 되감기(unwinding)를 시작하는 데 사용될 수 있습니다. 되감기를 하는 동안, 런타임은 모든 객체의 데스트럭터를 호출하여 해당 스레드가 소유한 모든 리소스를 해제합니다.

우리는 단일 스레드 프로그램만 다루고 있으므로, panic!은 프로그램이 패닉 메시지를 보고하고 종료하게 만듭니다.

// 정수 나눗셈(/)의 재구현
fn division(dividend: i32, divisor: i32) -> i32 {
    if divisor == 0 {
        // 0으로 나누기는 패닉을 트리거합니다
        panic!("0으로 나누기");
    } else {
        dividend / divisor
    }
}

// 메인 태스크
fn main() {
    // 힙 할당 정수
    let _x = Box::new(0i32);

    // 이 작업은 태스크 실패를 트리거합니다
    division(3, 0);

    println!("이 지점에는 도달하지 않습니다!");

    // 이 지점에서 `_x`가 파괴되어야 합니다
}

panic!이 메모리를 누수하지 않는지 확인해 봅시다.

$ rustc panic.rs && valgrind ./panic
==4401== Memcheck, a memory error detector
==4401== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==4401== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==4401== Command: ./panic
==4401==
thread '<main>' panicked at 'division by zero', panic.rs:5
==4401==
==4401== HEAP SUMMARY:
==4401==     in use at exit: 0 bytes in 0 blocks
==4401==   total heap usage: 18 allocs, 18 frees, 1,648 bytes allocated
==4401==
==4401== All heap blocks were freed -- no leaks are possible
==4401==
==4401== For counts of detected and suppressed errors, rerun with: -v
==4401== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)