Errors and Exceptions in Python
What are errors and exceptions?
When Python canβt execute your code, it stops and reports a problem.
- Syntax errors happen when Python canβt even parse the code.
- Exceptions happen while the program is running (runtime problems).
Syntax Error
A syntax error occurs when Python sees invalid code structure.
syntax_error.py
# Missing colon
if 10 > 5
print("10 is greater")syntax_error.py
# Missing colon
if 10 > 5
print("10 is greater")Typical output:
Traceback
File "syntax_error.py", line 2
if 10 > 5
^
SyntaxError: expected ':'Traceback
File "syntax_error.py", line 2
if 10 > 5
^
SyntaxError: expected ':'Exception (runtime error)
Example: division by zero.
zero_division.py
print(10 / 0)zero_division.py
print(10 / 0)Traceback
Traceback (most recent call last):
File "zero_division.py", line 1, in <module>
print(10 / 0)
ZeroDivisionError: division by zeroTraceback
Traceback (most recent call last):
File "zero_division.py", line 1, in <module>
print(10 / 0)
ZeroDivisionError: division by zeroHow to read a traceback
A traceback tells you:
- Where the error occurred (file and line number)
- The call stack (which functions were called)
- The exception type and message
Common exception types
NameErrorNameErrorβ variable not definedTypeErrorTypeErrorβ wrong type used (e.g., add str + int)ValueErrorValueErrorβ correct type, invalid value (e.g., int(βabcβ))IndexErrorIndexErrorβ list index out of rangeKeyErrorKeyErrorβ dict key missingFileNotFoundErrorFileNotFoundErrorβ file path not found
common_exceptions.py
# NameError
# print(x)
# TypeError
# print("age: " + 10)
# ValueError
# print(int("abc"))
# IndexError
# nums = [1, 2]
# print(nums[10])
# KeyError
# d = {"a": 1}
# print(d["missing"])
# FileNotFoundError
# open("missing.txt", "r")common_exceptions.py
# NameError
# print(x)
# TypeError
# print("age: " + 10)
# ValueError
# print(int("abc"))
# IndexError
# nums = [1, 2]
# print(nums[10])
# KeyError
# d = {"a": 1}
# print(d["missing"])
# FileNotFoundError
# open("missing.txt", "r")Next
In the next pages youβll learn:
- Handling exceptions with
try/excepttry/except - Cleaning up resources with
finallyfinallyand context managers - Creating custom exceptions
π§ͺ Try It Yourself
Exercise 1 β Catch a ValueError
Exercise 2 β Multiple Except Blocks
Exercise 3 β Raise a Custom Exception
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
