Error-handling
A Rust program must be maximally prepared to handle unforeseen errors, but unexpected things can always happen, like integer division by zero:
// see code in Chapter 5/code/error_div.rs let x = 3; let y = 0; x / y;
The program stops with the following message:
thread '<main>' panicked at 'attempted to divide by zero'
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...