Errors and Exceptions in Python
What are errors and exceptions?
Section titled “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
Section titled “Syntax Error”A syntax error occurs when Python sees invalid code structure.
# Missing colon
if 10 > 5
print("10 is greater")Typical output:
File "syntax_error.py", line 2
if 10 > 5
^
SyntaxError: expected ':'Exception (runtime error)
Section titled “Exception (runtime error)”Example: division by zero.
print(10 / 0)Traceback (most recent call last):
File "zero_division.py", line 1, in <module>
print(10 / 0)
ZeroDivisionError: division by zeroHow to read a traceback
Section titled “How 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
Section titled “Common exception types”NameError– variable not definedTypeError– wrong type used (e.g., add str + int)ValueError– correct type, invalid value (e.g., int(“abc”))IndexError– list index out of rangeKeyError– dict key missingFileNotFoundError– file path not found
# 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")In the next pages you’ll learn:
- Handling exceptions with
try/except - Cleaning up resources with
finallyand context managers - Creating custom exceptions
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Catch a ValueError
Section titled “Exercise 1 – Catch a ValueError”Exercise 2 – Multiple Except Blocks
Section titled “Exercise 2 – Multiple Except Blocks”Exercise 3 – Raise a Custom Exception
Section titled “Exercise 3 – Raise a Custom Exception”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading