Python Try and Except
try is where you put lines that might stop. except names the stop you will handle. except ZeroDivisionError runs only when the stop inside try has that name. After the whole try and except, the program goes on.
try:
print(1 / 0)
print("rice")
except ZeroDivisionError:
print("skip")
print("done")
The screen shows skip, then done. print(1 / 0) stops inside try. print("rice") is still inside try, so it does not run. Catching the stop does not go back and finish the rest of try. except writes skip. print("done") sits outside, so it runs after the catch. The program does not end on that stop.
The name has to match. Put print(tea) inside this try, and never give tea a value: the stop is NameError. except ZeroDivisionError does not handle that name. The program still stops. skip is not written, and neither is done. That line is not in the program on this page.
If every line inside try finishes, except does not run. The next program starts on its own. Nothing from the first screen is still here.
try:
print(8 / 2)
except ZeroDivisionError:
print("skip")
print("done")
The screen shows 4.0, then done. 4.0 is four, with a decimal point. There was no stop, so skip is not written. done still runs, because it sits outside the catch.
The lines under try and under except are indented. That indent is what puts them inside. print("done") is not indented under except, so it is not part of the catch. It runs when try finishes, and it also runs when the named stop is caught.
The next page is about causing a stop yourself. This page only catches a stop a line already hits, and only when the name matches.
What is written, and what is skipped
- What does the first program write?
- What happens to print("rice")?
- What does the second program write?
- What happens if print(tea) is inside try, tea was never given a value, and except only names ZeroDivisionError?
The name has to match
The first screen is skip, then done. rice does not run, because it is still inside try after the stop. The second screen is 4.0, then done, and skip is not written. A NameError is not caught by except ZeroDivisionError. done is outside, so it runs when the named stop is caught and when try finishes. The next page is about causing a stop yourself.
🧠 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