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.
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. π΄
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.
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!
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. π₯
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). β