Technology Exceptions | Python Tutorial

Learn with diagrams, code, systems and practical examples.

</>
TutorialsPythonExceptions
Functions & Modules · Chapter 19

Exceptions

Handle expected failures without hiding real bugs.

Why this matters

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.

IdeaUnderstand the purpose
CodeRun the smallest example
PracticeChange it yourself
SubjectVision learning pattern: understand the idea before memorizing syntax.

Small working example

Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.

Python
try:
    value = int("not-a-number")
except ValueError:
    value = 0

print(value)
Expected output
0
What to notice

The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.

Common beginner mistake

Mistake

Using a broad except block that swallows every error and makes debugging difficult.

Better approach

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.

  1. Handle a missing file.
  2. Raise a ValueError for invalid input in your own function.