Python Raising Exceptions
A stop used to show up because a line ran into a problem: dividing by zero, or a name that never received a value. raise is the other way. You write the stop. You choose its name, and you put a short message beside it.
raise ValueError("empty")
print("water")
The program stops on that raise. The screen shows ValueError and the word empty. print("water") does not run. Nothing is being divided. The stop is there because you wrote raise.
cups = 0
if cups < 1:
raise ValueError("empty")
print("water")
This program starts fresh. cups is 0. Zero is less than 1, so the if is entered and raise runs. The screen shows the same stop: ValueError, and the word empty. water is not written. Nothing on this page catches the stop, so the program ends there.
cups = 3
if cups < 1:
raise ValueError("empty")
print("water")
This one starts fresh too. cups is 3. Three is not less than 1, so the if is not entered. raise never runs. The screen writes water. There is no stop.
The raise line is indented under if. That indent is what puts it inside. print("water") is not indented under if. Once raise runs, the program has already stopped, so water is never reached. When the if is skipped, water runs.
The name you wrote is ValueError, not ZeroDivisionError. ZeroDivisionError was the name for dividing by zero. Here the number of cups is not usable, so the name is ValueError. If you catch this stop later, except has to say ValueError. except ZeroDivisionError does not catch it. That catch is not in the programs on this page. The words in quotes are the message. empty is what you chose to show next to the name. Python does not put None there instead.
The next page is files. This page only shows you causing a stop. It does not open a file.
Cups, and the stop you wrote
The first program stops on raise, and water is not written. With cups at 0, the if is entered and the same stop happens. With cups at 3, raise never runs and the screen writes water. The name of this stop is ValueError. The next page is files.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top