Learn with diagrams, code, systems and practical examples.
Exceptions
Handle expected failures without hiding real bugs.
Files may be missing, user input may be invalid, and network calls may fail. Programs need deliberate failure behavior.
Start with the idea
Exceptions interrupt normal flow when something goes wrong. try/except lets you handle specific failures. Catch the narrow exception you actually understand.
Small working example
Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.
try:
value = int("not-a-number")
except ValueError:
value = 0
print(value) Exceptions interrupt normal flow when something goes wrong. try/except lets you handle specific failures. Catch the narrow exception you actually understand.
- Exceptions represent failures.
- Catch specific exceptions.
- Recovery behavior should be intentional.
0The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.
Common beginner mistake
Using a broad except block that swallows every error and makes debugging difficult.
Catch specific exception types and handle only failures you can meaningfully recover from.
Quick recap
- Exceptions represent failures.
- Catch specific exceptions.
- Recovery behavior should be intentional.
Try it yourself
These are deliberately small. If you can complete them without copying the example, you are ready to continue.
- Handle a missing file.
- Raise a ValueError for invalid input in your own function.