![]() |
|
CHAPTER 17 — Errors & Exception Handling - Printable Version +- The Lumin Archive (https://theluminarchive.co.uk) +-- Forum: The Lumin Archive — Core Forums (https://theluminarchive.co.uk/forumdisplay.php?fid=3) +--- Forum: Courses — Structured Learning (https://theluminarchive.co.uk/forumdisplay.php?fid=69) +---- Forum: Beginner’s Guide to Coding — Python From Zero to Skill (https://theluminarchive.co.uk/forumdisplay.php?fid=72) +---- Thread: CHAPTER 17 — Errors & Exception Handling (/showthread.php?tid=235) |
CHAPTER 17 — Errors & Exception Handling - Leejohnston - 11-15-2025 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. 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:Example: Code: try:--- 17.3 Catching Specific Errors Better practice: Code: try:--- 17.4 Multiple Except Blocks Code: try:--- 17.5 Using else Runs ONLY if no error happens. Code: try:--- 17.6 Using finally Always runs — useful for closing files. Code: try:--- 17.7 Raising Your Own Errors For validation: Code: def set_age(age):--- 17.8 Validating User Input Safely Code: while True:This pattern is used in many real programs. --- 17.9 Handling File Errors Code: try:--- 17.10 Real-World Example — Safe Calculator Code: try:--- 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 |