Panics

A situation could occur that is so bad (like when dividing by zero) that it is no longer useful to continue running the program: we cannot recover from the error. In the case of such an error, we can invoke the panic!("message") macro, which will release all resources owned by the thread, report the message, and then make the program exit. We could improve the previous code, like this:

// see code in Chapter 5/code/errors.rs 
if (y == 0) { panic!("Division by 0 occurred, exiting"); } 
println!("{}", div(x, y)); 

The function div in the preceding code contains the following:

fn div(x: i32, y: i32) -> f32 { 
    (x / y) as f32 
} 

A number of other macros, like the assert! family, can also be used to signal such unwanted conditions:

assert!(x == 5); //thread <main> panicked at assertion failed: x == 5 
assert!( x == 5, "x is not equal to 5!"); 
// thread <main> panicked at "x is not equal to 5!" 
assert_eq!(x, 5); // thread '<main>' panicked at 'assertion failed: (left: `3`, right: `5`)', 

When the condition is not true, they result in a panic situation and exit. The error message given as the second parameter of assert! will be printed out, if it is present. Otherwise, the general message assertion failed is given. The assert! macro is mostly useful to test for pre and post conditions in and around functions.

Portions of code that normally would not be executed can contain the unreachable! macro, which will panic when it is executed:

unreachable!(); 
// thread '<main>' panicked at 'internal error: entered         // 
unreachable code'