17.6 panic!
panic! 매크로는 panic을 생성하고 그의 스택을 해제하기 시작한다. 해제 중에, 실행 환경은 모든 쓰레드의 소유 자산을 해제하며 모든 객체들의 소멸자들을 호출한다.
우리가 하나의 쓰레드를 처리한다면, panic!은 패닉 메시지를 출력하고 종료된다.
// Re-implementation of integer division (/)
fn division(dividend: i32, divisor: i32) -> i32 {
if divisor == 0 {
// 0으로 나누기는 패닉을 유발한다.
panic!("division by zero");
} else {
dividend / divisor
}
}
// The `main` task
fn main() {
// 정수에 힙 할당.
let _x = Box::new(0i32);
// 이 연산 작업은 실패할 것.
division(3, 0);
println!("This point won't be reached!");
// `_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)