A generic shield protects against everything, but sometimes we need to know what hit us.
Was it a fire trap? Or an ice trap? Hoppy needs to react differently depending on the danger.
Catching Specific Errors
You can tell Python to catch only specific types of errors. This is like having a "Fire Shield" and an "Ice Shield".
try:
# Some code
except ValueError:
print("Wrong value!")
except NameError:
print("Unknown name!")
1
The First Trap
The code int("Unlimited Power!") tries to turn text into a number, which causes a ValueError. Catch it and print "Spell text invalid!".
2
The Second Trap
Code like 100 / 0 causes a ZeroDivisionError. chaos. Add a second except block for it and print "Cannot divide by zero!".
Using specific exceptions is better than a bare except:, because it keeps you from accidentally hiding bugs you didn't expect!
Suggested SolutionExpandCollapse
ExpandCollapse
Solution:
try:
spell_power = int("Unlimited Power!")
except ValueError:
print("Spell text invalid!")
try:
energy = 100 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")Advanced TipsWant more? Click to expandClick to collapse
F. Knowing Your Enemy
- Common Python Exceptions:
IndexError: Looking for item 10 in a list of 5.KeyError: Looking for a dictionary key that isn't there.FileNotFoundError: Reading a file that doesn't exist.
Loading...
Terminal
Terminal
Ready to run...