Phase 2: Programming Fundamentals II · ~35 minutes · Python · uv
Exceptions — Handling Things Going Wrong
A bare except: doesn't handle errors. It hides them — including the ones you actually needed to see.
Hiring signal: Never writes a bare except:, and always catches the most specific exception type the situation calls for
What you will learn
- Use try/except/else/finally to handle errors your program can anticipate
- Catch specific exception types instead of using a bare except:
- Explain why silently swallowing all exceptions is more dangerous than not handling errors at all
- Predict which except block fires when multiple are present
Introduction
Type: Learn Languages: Python Prerequisites: Lesson 04 (Reading and Writing Files) Time: ~35 minutes
Objective
Learning objectives
- Use
try/except/else/finally to handle errors your program can anticipate - Catch specific exception types instead of using a bare
except: - Explain why silently swallowing all exceptions is more dangerous than not handling errors at all
- Predict which
except block fires when multiple are present
What you're building
A script (safe_file_reader.py) that:
- Defines a function
read_config(path) that opens and reads a file, wrapped in try/except - Catches
FileNotFoundError specifically, printing a clear message (f"Config file not found: {path}") and returning None — not a bare except: - Calls it once with a real file that exists (create one first) and once with a path that doesn't, showing both behaviors
- Contains a comment demonstrating the
"appel"/get_price silent-typo bug from this lesson, and the corrected version that catches KeyError specifically instead of everything
Given except ValueError: followed later by except Exception: (in that order) inside the same try block, what happens if the code raises a TypeError?
Python checks except blocks top to bottom and uses the first one whose exception type matches (including matching a parent type — every built-in exception is a kind of Exception). TypeError doesn't match ValueError at all, so that block is skipped. It does match Exception, since TypeError is a form of Exception, so the second block catches it. This is the same ordering principle as the ZeroDivisionError/Exception example above, just with the general catch-all placed correctly at the end instead of incorrectly at the start.
Unlock the full lesson
You've read the first 2 sections. The rest of this lesson covers The Problem, Check Yourself, Key Terms & Next — plus a hands-on lab, quiz, and project artifact.
Create a free account to unlock Phase 0 and Phase 1 of every course — no credit card.
Browse all courses · View pricing · DeVenture Academy