Files
100-exercises-to-learn-rust/book/src/02_basic_calculator/04_panics.md
Luca Palmieri 1aae615bb4 Automatically add exercise links to sections. (#52)
We use an mdbook preprocessor to automatically generate links to the relevant exercise for each section.
We remove all existing manual links and refactor the deploy process to push the rendered book to a branch.
2024-05-24 18:15:38 +02:00

1.8 KiB
Raw Blame History

Panics

Lets go back to the speed function you wrote for the “Variables” section. It probably looked something like this:

fn speed(start: u32, end: u32, time_elapsed: u32) -> u32 {
    let distance = end - start;
    distance / time_elapsed
}

If you have a keen eye, you might have spotted one issue1: what happens if time_elapsed is zero?

You can try it out on the Rust playground!
The program will exit with the following error message:

thread 'main' panicked at src/main.rs:3:5:
attempt to divide by zero

This is known as a panic.
A panic is Rusts way to signal that something went so wrong that the program cant continue executing, its an unrecoverable error2. Division by zero classifies as such an error.

The panic! macro

You can intentionally trigger a panic by calling the panic! macro3:

fn main() {
    panic!("This is a panic!");
    // The line below will never be executed
    let x = 1 + 2;
}

There are other mechanisms to work with recoverable errors in Rust, which well cover later. For the time being well stick with panics as a brutal but simple stopgap solution.

Further reading


  1. Theres another issue with speed that well address soon enough. Can you spot it?↩︎

  2. You can try to catch a panic, but it should be a last resort attempt reserved for very specific circumstances.↩︎

  3. If its followed by a !, its a macro invocation. Think of macros as spicy functions for now. Well cover them in more detail later in the course.↩︎