Phase 3: The Reflex.
Our Golem is enthusiastic. Too enthusiastic. It works until its battery hits 0, then it dies (the program crashes).
Biological creatures have pain to tell them to stop. We need to give our Golem a similar Reflex (Exception).
The Safety Check
We need to modify the work() method. Before doing anything, it should check its energy.
- Check: If
energy <= 0, stop immediately! - Alarm: Raise a
ValueErrorsaying "Low Battery".
Then, in our main loop, we catch this alarm and recharge it.
def work(self):
# 1. Calculate potential loss
loss = random.randint(5, 15)
# 2. Check if it would drain us completely
if self.energy - loss < 0:
raise ValueError("Low Battery!")
# 3. Normal Work
# ...
1
Modify work()
Add the check at the top of the work method. Raise ValueError if energy is low.
2
Handle the Crisis
In the main code, wrap the bob.work() call in a try...except block.
3
Recharge
In the except block:
- Print "Recharging...".
- Set
bob.energy = 100.
Notice: We raise the error inside the class, but we catch it outside. This is how components communicate failure to the main system.
Suggested SolutionExpandCollapse
ExpandCollapse
Solution:
import random
class Golem:
def __init__(self, name):
self.name = name
self.energy = 20 # Low capacity for testing
def work(self):
# 1. Calculate the cost first
loss = random.randint(5, 15)
# 2. Check if we can afford it
if self.energy < loss:
raise ValueError("Low Battery!")
# 3. Deduct only if safe
self.energy -= loss
print(f"{self.name} works. Energy: {self.energy}")
bob = Golem("Bob")
# Simulate work
for i in range(10):
try:
bob.work()
except ValueError:
print("Recharging...")
bob.energy = 20Loading...
Terminal
Terminal
Ready to run...