Python Exceptions: Read Errors and Know Their Types
What Is an Exception in Python?
An exception is an error that happens while your program is running. Python stops at the line that fails and tells you what went wrong. The lines before it have already run; the lines after it never run.
print("Start")
price = 300
people = 0
print(price / people)
print("End")Start ZeroDivisionError: division by zero
Start was printed, because line 1 ran fine. Then line 4 tried to divide by zero, and the program stopped. End never appeared.
Think of it like a smoke alarm in a kitchen. Everything is fine until the moment something burns. Then the alarm goes off, cooking stops, and the alarm tells you what the problem is.
Two kinds of errors
You met both kinds in chapter 1. Now they get proper names:
| Kind | When Python finds it | Examples |
|---|---|---|
| Syntax error | before the first line runs | a missing colon, a missing bracket |
| Exception | while the program runs, at the line that fails | dividing by zero, int("abc") |
A syntax error means Python can't even read your code, so nothing runs, not even line 1:
print("Start")
print("Hi"SyntaxError: '(' was never closedThe rules
- An exception stops the program at the line that fails.
- Everything before that line has already happened.
- Every exception has a type, like
ZeroDivisionError, and a message, likedivision by zero.
Common beginner doubt: "Does an exception mean my code is wrong?" Not always. Sometimes it's a bug, like a typo in a name. But sometimes the code is fine and the input is bad: the user types abc where you asked for a number. You can't stop users from typing that. What you can do is handle the exception, so your program reacts calmly instead of crashing. That's what this chapter is about.
An exception is an error at run time: Python stops at that line, and the lines after it never run.