Should I Panic?
Now you know two ways to handle trouble: the big emergency stop (panic!) and the calm
βsuccess or oopsβ box (Result). But which one should you pick? π€
Hereβs a simple way to decide, like choosing between a fire alarm and just asking for help.
Expected oops vs. real disasters
Some problems are totally normal. If you ask someone to type a number and they type
βbanana,β thatβs not a disaster β you just politely ask again. Thatβs a job for Result.
But if part of your program breaks a rule that should be impossible, thatβs a real bug. Panicking is okay there, because it means βsomething is deeply wrong, stop and let me fix it.β π οΈ
Result is like a spilled drink β annoying, but you grab a towel
and clean up. A panic is like the smoke alarm going off π¨ β you stop
everything because it's serious.
Quick but risky: unwrap and expect
Sometimes you have a Result and you just want the success value quickly. Two shortcuts
grab it fast: unwrap() and expect(). But thereβs a catch β if the Result was an Err,
they panic and crash your program!
Here "10" really is a number, so unwrap() happily hands us 10. But if it had been
"oops", the program would crash! expect("a nice message") works the same way but lets
you add your own warning text.
unwrap() and expect() are fine for tiny tests and quick
experiments, but they're risky in real programs because they crash on Err.
In real code, prefer match or ?.
unwrap() as saying "I'm sure
this worked!" If you're wrong, the program panics. Only say it when you're truly sure. π¦
"10" to another number like "99" and press
βΆ Run. The unwrap still works because it's a real number!
Quick quiz
When should you use panic! instead of Result?
Right! Panic is for true bugs. Expected oops, like bad typing, should
use Result. π€
unwrap() and expect() are quick but crash on
Err, so use them carefully. You've finished World 9 β you now know how to
handle mistakes like a pro! Next up: a brand-new adventure awaits. π