πŸ€”
World 9 Β· Oops! Handling Mistakes

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.

The Big Idea Use a Result for problems you expect β€” like a missing file or someone typing the wrong thing. Use panic only for bugs that should never happen β€” the "this is impossible!" kind.

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.” πŸ› οΈ

Think of it like this… A 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.

Watch out! 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 ?.
Ferris says: Think of unwrap() as saying "I'm sure this worked!" If you're wrong, the program panics. Only say it when you're truly sure. πŸ¦€
Try this! Change "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. πŸ€”

You learned… Use Result for problems you expect and panic only for impossible bugs. 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. πŸš€