Lesson 03
Built-in Exceptions in Python — ValueError, TypeError, and More
Master the most common Python exception classes — when each is raised, how PVM creates exception objects, and how to catch specific types.
Lesson goal: Python already provides dozens of ready-made exception classes. Instead of creating every error yourself, you use these built-in exceptions for universal programming problems.
What you will learn
- Built-in vs custom exceptions
- The 7 most common Python exception classes
- What triggers each exception
- How exceptions are objects
- How to catch specific exception types
Before we begin — Think like a doctor
Imagine you are a doctor diagnosing patients. Every patient has different symptoms. Likewise, every programming error has a different exception class.
Key idea: The exception class tells Python exactly what kind of problem occurred.
1. Two types of exceptions
Python exceptions are divided into two categories.
Easy comparison
| Feature | Built-in | Custom |
|---|---|---|
| Created by | Python | Developer |
| Purpose | Universal problems | Business rules |
| Examples | ValueError |
InvalidPinError |
| Available immediately | ✅ Yes | ❌ You create it |
Today's lesson focuses only on built-in exceptions. Custom exceptions come in a later lesson.
2. The built-in exception family
Every exception is actually a class.
Think of it like a family tree:
BaseException→ parent of all exceptionsException→ main family for program errorsValueError,KeyError, etc. → children you catch inexcept
3. The 7 most common built-in exceptions
These are the exceptions you will use almost every day.
ValueError — most common
Raised when the value is invalid, even though the type is correct.
age = int("abc") # ValueErrorReal life: User types "twenty" into an age field.
TypeError
Raised when you perform an operation on incompatible data types.
"Hello" + 5 # TypeErrorReal life: Adding text and numbers together.
ZeroDivisionError
Raised when dividing by zero.
10 / 0 # ZeroDivisionErrorReal life: Average calculation where total students = 0.
IndexError
Raised when accessing a list or tuple position that does not exist.
nums = (10, 20)
print(nums[5]) # IndexErrorReal life: Opening the 10th photo when only 2 exist.
KeyError
Raised when a dictionary key does not exist.
student = {"name": "Sam"}
print(student["age"]) # KeyErrorReal life: Looking for "salary" in employee data that only contains "name".
NameError
Raised when using a variable that has never been created.
print(total) # NameError — total was never assignedReal life: Using a variable before assigning it.
FileNotFoundError
Raised when opening a file that does not exist.
open("marks.txt") # FileNotFoundErrorReal life: User selects a deleted document.
4. Exception explorer — IndexError
colors = ["red", "blue"]
print(colors[9])Raised because: Index 9 is outside the list. Valid indices are 0 and 1 only.
Try changing 9 to 0 or 1 in the playground — no error. Change it back to 9 — IndexError.
5. Exceptions are objects (very important)
Many beginners think exceptions are just messages. They are not. They are objects created by the Python Virtual Machine (PVM).
Example
try:
int("xyz")
except ValueError as err:
print(type(err))
print(err)Output:
<class 'ValueError'>
invalid literal for int() with base 10: 'xyz'| Code | Meaning |
|---|---|
err |
Exception object |
type(err) |
Returns the class |
print(err) |
Returns the technical message |
6. How Python chooses the correct exception
Imagine a security guard checking ID cards. The exception class must match.
Python compares:
- Raised exception →
ValueError except ValueError→ Match ✅ — handler runsexcept KeyError→ No match ❌ — skipped
Always catch the specific exception type when you can.
7. Real-world case study — Student portal
Imagine a university marks portal.
| User action | Exception |
|---|---|
Types "A+" as age |
ValueError |
Adds "Math" + 90 |
TypeError |
| Divides by zero students | ZeroDivisionError |
| Opens 100th student | IndexError |
Looks for "chemistry" key |
KeyError |
The exception tells you exactly what went wrong.
8. Playground challenge
Predict the output before running the playground:
demos = [
("ValueError", lambda: int("abc")),
("ZeroDivisionError", lambda: 10 / 0),
("TypeError", lambda: "hi" + 5),
("IndexError", lambda: [1, 2][9]),
("KeyError", lambda: {"a": 1}["z"]),
]
for name, fn in demos:
try:
fn()
except Exception as err:
print(name, type(err).__name__)Expected output
ValueError ValueError
ZeroDivisionError ZeroDivisionError
TypeError TypeError
IndexError IndexError
KeyError KeyErrorWhy does every line print? Because each exception is caught inside the loop, allowing the program to continue instead of crashing.
Quick reference sheet
| Exception | Cause | Example |
|---|---|---|
ValueError |
Invalid value | int("abc") |
TypeError |
Wrong type | "a" + 5 |
ZeroDivisionError |
Divide by zero | 10 / 0 |
IndexError |
Invalid list index | lst[99] |
KeyError |
Missing dictionary key | d["x"] |
NameError |
Undefined variable | print(x) |
FileNotFoundError |
Missing file | open("a.txt") |
Interview questions
Q1. What is the difference between ValueError and TypeError?
- ValueError: Correct type, wrong value (e.g.
int("abc")). - TypeError: Wrong data type used in an operation (e.g.
"a" + 5).
Q2. Why is KeyError different from IndexError?
IndexError→ lists and tuples (position)KeyError→ dictionaries (key)
Q3. What does except ValueError as err mean?
err is the exception object created by the Python Virtual Machine when the error occurs.
Key takeaways
- Built-in exceptions are predefined classes provided by Python
- Every runtime error becomes an exception object
exceptmust match the correct exception class- Custom exceptions are for business rules; built-in exceptions handle universal programming problems
- Next:
tryandexceptBasics — syntax, multipleexceptblocks, and your first robust programs
Loading playground…
Check your understanding
Built-in exceptions quiz
int("abc") raises:
1 / 10