Part 06 / Topic 1 of 10
Syntax errors vs exceptions
- A syntax error means Python cannot even read your code (a missing
:or bracket). Nothing runs. Fix the code. - An exception happens while the code runs (dividing by zero, a missing file). You can handle it.
Think of a recipe: a syntax error is a recipe written in broken language, so the cook cannot start. An exception is running out of milk halfway through cooking.
Real-world example: a typo vs a bad value from a user.
# Syntax error: the file will not run at all
# if total > 100
# print("Free delivery")
# SyntaxError: expected ':'
# Exception: the code is fine, but the value is bad
print(int("42")) # 42
print(int("forty")) # crashes: ValueError: invalid literal for int() with base 10: 'forty'
| Syntax error | Exception | |
|---|---|---|
| When | Before running | While running |
| Cause | Code is written wrong | A bad value or situation |
Can try catch it? |
No | Yes |
๐ Going deeper: Python first compiles the whole file to bytecode (Part 1). A syntax error is found at that step, so no line runs.
SyntaxErroris itself an exception, so you can catch it when code is compiled later, for example byeval()orimport, but never in the same file.
Done here? The practice set for Part 6 โ 7 exercises with solutions โ is on the part page.