We identified the errors, but how do we stop them from crashing our program?
Imagine Hoppy walking through a minefield. Instead of hoping there are no mines, we can give Hoppy a Shield. If a mine explodes, the shield absorbs the blast, and Hoppy keeps walking.
The try and except Spell
This spell has two parts:
- try: "Attempt to do this risky thing."
- except: "If it fails/crashes, do this instead of dying."
try:
# Risky code
print(1 / 0)
except:
# Backup plan
print("ZeroDivisionError blocked!")
1
Cast the Shield
Wrap the loot = open_chest(13) line inside a try: block. Remember to indent!
2
Handle the Trap
Add an except: block. Inside it, print "Shield blocked the trap!".
3
Run it
Run the code. Instead of seeing a scary red error trace, you should see your custom message.
Without try/except, an error stops your program immediately. With it, your program can continue running even after an accident!
Suggested SolutionExpandCollapse
ExpandCollapse
Solution:
try:
loot = open_chest(13)
print("Loot found: " + loot)
except:
print("Shield blocked the trap!")Advanced TipsWant more? Click to expandClick to collapse
F. Shield Mechanics
- Don't shield everything: Only use
try/exceptaround code that might crash (like reading files, network requests, or user input). - Silence is dangerous: If you use
except:without printing anything, you might hide real bugs. Always log something!
Loading...
Terminal
Terminal
Ready to run...