We have learned how to catch errors. But sometimes, we need to create them.
Why? Because sometimes things are technically correct (for Python) but wrong for our airship rules. Like trying to fly with 0 fuel.
The raise Spell
The raise keyword lets you sound the alarm manually. You can stop the program and scream "Something is wrong!"
def enter_club(age):
if age < 18:
# Stop everything! Invalid!
raise ValueError("Too young!")
print("Welcome.")
1
Check the Energy
In the check_engine function, write an if statement to check if energy is less than 10.
2
Raise the Alarm
Inside the if, use raise ValueError("Energy too low!").
3
Test the System
Run the code. The second call check_engine(5) should trigger your alarm, and our try/except block will catch it and print the warning!
You are now the master of errors. You can handle them (except) and create them (raise).
Suggested SolutionExpandCollapse
ExpandCollapse
Solution:
def check_engine(energy):
print("Checking engine with energy: " + str(energy))
if energy < 10:
raise ValueError("Energy too low!")
print("Engine stable.")
try:
check_engine(50)
check_engine(5) # This triggers the alarm
except ValueError as e:
print("Alarm caught: " + str(e))Advanced TipsWant more? Click to expandClick to collapse
F. Custom Alarms
- You can raise any built-in error using
raise. - Professional Python programs use
raiseto signal that a function cannot do its job properly given the inputs.
Loading...
Terminal
Terminal
Ready to run...