Errors & Exceptions
Things go wrong โ a file is missing, input is nonsense, the network is down. Handling errors gracefully with try/except is what separates a fragile script from a robust program.
Every real program meets things that go wrong: a file that isn't there, a user typing letters where a number should be, a network that drops. A beginner script crashes; a robust program anticipates trouble and handles it gracefully. Python's try/except is the tool - and, importantly, knowing when to handle an error versus when to let it crash loudly.
try / except: catch what you expect
Wrap risky code in try, and handle specific problems in except. The key word is specific - catch the error you expect, not everything.
try:
age = int(input("Your age: "))
except ValueError:
print("That wasn't a number - try again.")
# handle a missing file gracefully
try:
with open("config.txt") as f:
settings = f.read()
except FileNotFoundError:
settings = "" # sensible defaultexcept:. Catching everything (a bare except: or except Exception) hides bugs - it swallows the typos and logic errors you actually want to know about, along with the one problem you meant to handle. Catch the specific thing you expect (ValueError, FileNotFoundError, KeyError...) and let everything else surface. An error you didn't anticipate crashing loudly is a feature: it tells you exactly what to fix.When NOT to catch
Handling errors doesn't mean silencing them. Sometimes the right response is to let the program stop - a crash with a clear message beats limping on with bad data.
| Situation | Right response |
|---|---|
| User typed bad input | Catch it, ask again |
| Optional file missing | Catch it, use a default |
| A bug in your logic | Let it crash - you need to know |
| Data is corrupt/impossible | Fail loudly, don't guess |
The goal is a program that handles the expected and fails clearly on the unexpected. Silently swallowing errors ('except: pass') is one of the most common ways bugs hide for months - avoid it.
Fail gracefully - or loudly
- try/except handles trouble you can anticipate (bad input, missing file).
- Be specific - catch ValueError/FileNotFoundError, not a bare except.
- Let real bugs crash - a clear crash tells you what to fix.
- Never 'except: pass' - silently swallowing errors hides bugs for months.
๐งฉ Do it with LarzOS
Turn this lesson into action with the exact free tools and AI workflows for the job:
๐ฏ Key takeaways
- Robust programs anticipate what can go wrong and handle it, instead of crashing on everything.
- Wrap risky code in try/except - but catch SPECIFIC exceptions, not a bare except.
- Letting an unexpected error crash loudly is a feature - it tells you what to fix.
- Never silently swallow errors with 'except: pass' - it hides bugs for months.
Frequently asked
Why is catching every exception with a bare 'except:' a bad idea?
Because it hides the errors you most need to see. A bare 'except:' (or 'except Exception') catches everything - not just the specific problem you were trying to handle, but also typos, logic mistakes, wrong variable names, and every other bug. Those bugs then get silently swallowed instead of crashing and pointing you at the problem, so they hide, sometimes for months, until they cause something worse. It also catches things you almost never mean to, like the user pressing Ctrl-C to quit. The fix is to catch specifically: name the exact exception you expect (ValueError for bad number input, FileNotFoundError for a missing file, KeyError for a missing dict key) so you handle that one case and let everything unexpected surface loudly. Specific catches make your error handling intentional rather than a blanket that hides problems.
Isn't the goal to stop my program from ever crashing?
No - and this surprises people. A crash isn't inherently bad; an unclear crash, or worse, silently continuing with wrong data, is what's bad. The real goal is a program that handles the situations you can anticipate (bad input, a missing optional file) gracefully, and fails clearly and immediately on the situations you can't. When there's a genuine bug in your logic or the data is impossible, letting it crash with a clear error message is exactly right: it tells you precisely what and where to fix, and it stops the program before it corrupts data or produces nonsense. Trying to prevent all crashes by catching everything just converts loud, informative failures into silent, mysterious ones. Handle the expected, fail loudly on the unexpected - that's robustness.
Related lessons
Working with Files
Real programs read and write files โ save data, load it back, process a document. It's simโฆ
Intermediate PythonObjects & Classes: Your Own Types
Classes let you bundle data and the behaviour that goes with it into your own types โ a waโฆ
Intermediate PythonBuild a Real Tool
Put it all together โ functions, files, error handling and clean idioms โ into a small comโฆ