πŸ’₯
World 9 Β· Oops! Handling Mistakes

When Things Break (panic!)

Imagine you’re playing a board game and suddenly a piece is missing. You can’t keep going, so everyone shouts β€œSTOP!” and the game ends. In Rust, that big STOP is called a panic. πŸ’₯

When a Rust program panics, it stops right away because something went really, really wrong. It’s like an emergency brake on a bike β€” you only pull it when you truly must.

The Big Idea A panic is Rust's emergency stop. When your program panics, it ends immediately and tells you what went wrong. We use the panic! command to make one happen on purpose.

Pulling the emergency brake

You can cause a panic yourself with panic!. You put a message inside it to explain what happened. Watch what comes out!

See how the last println! never happened? Once the program panics, it stops dead. Everything after the panic is skipped, like slamming the brakes on a scooter. πŸ›΄

Ferris says: A panic isn't a punishment! It's Rust protecting you. It would rather stop than keep going and make a bigger mess. πŸ¦€

When panics happen by accident

Sometimes Rust panics on its own when you ask for something impossible β€” like skipping to track 10 on a playlist that only has 3 songs. 🎡

If you have a list with 3 things and you ask for thing number 100, Rust says β€œthat doesn’t exist!” and panics. It’s protecting you from reaching for something that isn’t there.

Watch out! Save panic! for true emergencies β€” bugs that should never happen. For everyday "oops" moments (like someone typing the wrong thing), there's a gentler way that we'll meet very soon!
Try this! Change the message inside panic!("oh no!") to your own warning, like "the save file is corrupted!" πŸ’Ύ Press β–Ά Run and watch your message appear in the panic line.

Quick quiz

What happens when a program hits panic!?

Yes! A panic is the emergency stop β€” the program ends as soon as it happens. πŸ’₯

You learned… A panic is Rust's emergency stop for true disasters, and panic!("message") ends the program and prints your message. But most "oops" moments aren't emergencies! Next up: a friendlier way to handle problems β€” Success or Oops (Result). βœ