Python Exceptions
Some lines cannot be finished. Python stops on that line and gives the stop a name. 8 / 2 can be finished: two people share 8, and each share is four. 1 / 0 cannot: there is nobody to hand the 1 to. The name of that stop is ZeroDivisionError.
print(8 / 2)
print(1 / 0)
print("rice")
The screen shows 4.0, and then the program stops. 4.0 is four, written with a decimal point, because this division writes the number that way. rice is not written. The line after the stop does not run.
Read the name at the end of the message. ZeroDivisionError means this line divided by zero. A different problem gets a different name. The name is how you tell the problems apart.
print(tea) stops when the name tea was never given a value. The name of that stop is NameError. print("tea") is a different line: the quotes make it text, and that text would be written. Without the quotes, Python looks for a name.
Python does not invent a value and keep going. It does not write None and then rice. The stop is the end of this program.
📊 Which stop, or no stop
| Line | What happens |
|---|---|
| 1 / 0 | the program stops, and the name is ZeroDivisionError |
| print(tea), and tea was never given a value | the program stops, and the name is NameError |
| 8 / 2 | 4.0 is written, and the program does not stop |
| print("rice") after 1 / 0 | that line does not run |
Division itself is allowed. 8 / 2 writes 4.0 and does not stop. The zero on the right of the slash is what stops the second line.
The next page catches a stop, so the lines after it can still run. This page only reads the name of the stop.
What the stop is called
- What is written before the program stops?
- What is the name of the stop on 1 / 0?
- What happens to print("rice")?
- If you write print(tea) and tea was never given a value, what is the name of the stop?
- What does 8 / 2 do?
Two names, two problems
The screen shows 4.0, then the program stops. rice is not written. 1 / 0 is named ZeroDivisionError. A name that was never given a value is named NameError. 8 / 2 does not stop. The next page catches a stop so later lines can still run.
🧠 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