November 2017
Intermediate to advanced
264 pages
5h 45m
English
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 ...
Read now
Unlock full access