panic!

The panic! macro can be used to generate a panic and start unwinding
its stack. While unwinding, the runtime will take care of freeing all the
resources owned by the thread by calling the destructor of all its objects.

Since we are dealing with programs with only one thread, panic! will cause the
program to report the panic message and exit.

  1. // Re-implementation of integer division (/)
  2. fn division(dividend: i32, divisor: i32) -> i32 {
  3. if divisor == 0 {
  4. // Division by zero triggers a panic
  5. panic!("division by zero");
  6. } else {
  7. dividend / divisor
  8. }
  9. }
  10. // The `main` task
  11. fn main() {
  12. // Heap allocated integer
  13. let _x = Box::new(0i32);
  14. // This operation will trigger a task failure
  15. division(3, 0);
  16. println!("This point won't be reached!");
  17. // `_x` should get destroyed at this point
  18. }

Let’s check that panic! doesn’t leak memory.

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