Raising errors
Python · Unit 9: Errors and exceptions
- Full plan
- Python
- 10 exercises
raise throws an error on purpose. It's for when data arrives that makes no sense: better to stop with a clear message than to carry on and give a wrong result.
You write the error type and, in parentheses, the message.
def area(side):
if side < 0:
raise ValueError("side < 0")
return side * side
print(area(3))Prints
9
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Multiple choice
What happens with
area(-2)?2. Predict the output
as eworks with Python's own errors too. What does it print?3. Predict the output
What does this code print?
4. Complete the code
Complete it so withdrawing more than there is warns you with an error.
5. Multiple choice
average(grades)gets an empty list. Which line warns best?6. Find the bug
validateshould reject ages below 0 or above 120. Which line has the bug?7. Multiple choice
What does this function do?
8. Put the lines in order
Put the program in order.
payrejects amounts of 0 or less, and thetrycatches the warning.9. Write the code
Add an
iftoticketsthat raisesValueError("no tickets")whennis less than 1.10. Predict the output
Here the
tryis outside thefor. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.