11-15-2025, 10:41 PM
Chapter 17 — Errors & Exception Handling
Programs crash when something unexpected happens. Exception handling prevents that — keeping your software safe, professional, and user-friendly.
Every programmer makes mistakes.
Every user enters bad input.
Every program encounters unexpected situations.
Python gives us tools to handle all of this safely.
---
17.1 Common Types of Errors
SyntaxError
Code is written incorrectly.
TypeError
Wrong type used.
ValueError
Bad value inside correct type.
ZeroDivisionError
Division by zero.
---
17.2 Try & Except
Basic structure:
Example:
---
17.3 Catching Specific Errors
Better practice:
---
17.4 Multiple Except Blocks
---
17.5 Using else
Runs ONLY if no error happens.
---
17.6 Using finally
Always runs — useful for closing files.
---
17.7 Raising Your Own Errors
For validation:
---
17.8 Validating User Input Safely
This pattern is used in many real programs.
---
17.9 Handling File Errors
---
17.10 Real-World Example — Safe Calculator
---
17.11 Mini Project — Safe Login
Requirements:
• ask for username
• ask for password
• catch empty input
• catch spaces
• deny login if invalid
Example errors to catch:
• ValueError (empty input)
• anything unexpected
---
17.12 Challenge — Fault-Tolerant Data Loader
Your program must:
1. Ask for a filename
2. Try to open it
3. Catch:
• FileNotFoundError
• PermissionError
• UnicodeDecodeError
4. If opened successfully:
• read file
• show the number of lines
BONUS:
Ask the user to “try again” without crashing.
---
17.13 Chapter Summary
• try/except prevents crashes
• catch specific errors for clarity
• else runs when no error occurs
• finally always runs
• raising errors helps validate values
• safe loops ensure correct user input
Next:
Chapter 18 — Object-Oriented Programming (Beginner Overview)
This is where we introduce *classes*, *objects*, and the structure behind real-world software.
---
Written and Compiled by Lee Johnston — Founder of The Lumin Archive
Programs crash when something unexpected happens. Exception handling prevents that — keeping your software safe, professional, and user-friendly.
Every programmer makes mistakes.
Every user enters bad input.
Every program encounters unexpected situations.
Python gives us tools to handle all of this safely.
---
17.1 Common Types of Errors
SyntaxError
Code is written incorrectly.
Code:
print("Hello" # missing parenthesisTypeError
Wrong type used.
Code:
"age" + 5ValueError
Bad value inside correct type.
Code:
int("hello")ZeroDivisionError
Division by zero.
Code:
10 / 0---
17.2 Try & Except
Basic structure:
Code:
try:
# code that may fail
except:
# what to do if it failsExample:
Code:
try:
num = int(input("Enter a number: "))
except:
print("That was not a valid number.")---
17.3 Catching Specific Errors
Better practice:
Code:
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero.")---
17.4 Multiple Except Blocks
Code:
try:
value = int(input("Enter age: "))
except ValueError:
print("Please enter numbers only.")
except TypeError:
print("Type error occurred.")---
17.5 Using else
Runs ONLY if no error happens.
Code:
try:
age = int(input("Age: "))
except ValueError:
print("Invalid age.")
else:
print(f"You are {age} years old.")---
17.6 Using finally
Always runs — useful for closing files.
Code:
try:
f = open("data.txt")
except FileNotFoundError:
print("File missing.")
finally:
print("Program finished.")---
17.7 Raising Your Own Errors
For validation:
Code:
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
return age---
17.8 Validating User Input Safely
Code:
while True:
try:
num = int(input("Enter a number: "))
break
except ValueError:
print("Numbers only, try again.")This pattern is used in many real programs.
---
17.9 Handling File Errors
Code:
try:
with open("notes.txt") as f:
print(f.read())
except FileNotFoundError:
print("File not found.")---
17.10 Real-World Example — Safe Calculator
Code:
try:
a = float(input("A: "))
b = float(input("B: "))
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Numbers only.")---
17.11 Mini Project — Safe Login
Requirements:
• ask for username
• ask for password
• catch empty input
• catch spaces
• deny login if invalid
Example errors to catch:
• ValueError (empty input)
• anything unexpected
---
17.12 Challenge — Fault-Tolerant Data Loader
Your program must:
1. Ask for a filename
2. Try to open it
3. Catch:
• FileNotFoundError
• PermissionError
• UnicodeDecodeError
4. If opened successfully:
• read file
• show the number of lines
BONUS:
Ask the user to “try again” without crashing.
---
17.13 Chapter Summary
• try/except prevents crashes
• catch specific errors for clarity
• else runs when no error occurs
• finally always runs
• raising errors helps validate values
• safe loops ensure correct user input
Next:
Chapter 18 — Object-Oriented Programming (Beginner Overview)
This is where we introduce *classes*, *objects*, and the structure behind real-world software.
---
Written and Compiled by Lee Johnston — Founder of The Lumin Archive
