Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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.

Intermediate35 min
Built-in exceptions hero Module 15 Lesson 3 MahiDev

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.

Error diagnosis symptom abc int ValueError divide zero IndexError

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.

Built-in vs custom exceptions MahiDev comparison

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.

Exception family tree BaseException Exception ValueError TypeError

Think of it like a family tree:

  • BaseException → parent of all exceptions
  • Exception → main family for program errors
  • ValueError, KeyError, etc. → children you catch in except

3. The 7 most common built-in exceptions

These are the exceptions you will use almost every day.

Seven common built-in exceptions MahiDev reference cards

ValueError — most common

Raised when the value is invalid, even though the type is correct.

python
age = int("abc")  # ValueError

Real life: User types "twenty" into an age field.

TypeError

Raised when you perform an operation on incompatible data types.

python
"Hello" + 5  # TypeError

Real life: Adding text and numbers together.

ZeroDivisionError

Raised when dividing by zero.

python
10 / 0  # ZeroDivisionError

Real life: Average calculation where total students = 0.

IndexError

Raised when accessing a list or tuple position that does not exist.

python
nums = (10, 20)
print(nums[5])  # IndexError

Real life: Opening the 10th photo when only 2 exist.

KeyError

Raised when a dictionary key does not exist.

python
student = {"name": "Sam"}
print(student["age"])  # KeyError

Real life: Looking for "salary" in employee data that only contains "name".

NameError

Raised when using a variable that has never been created.

python
print(total)  # NameError — total was never assigned

Real life: Using a variable before assigning it.

FileNotFoundError

Raised when opening a file that does not exist.

python
open("marks.txt")  # FileNotFoundError

Real life: User selects a deleted document.


4. Exception explorer — IndexError

IndexError explorer colors list index out of range
python
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).

Exception object ValueError PVM except as err

Example

python
try:
    int("xyz")
except ValueError as err:
    print(type(err))
    print(err)

Output:

text
<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.

except ValueError match KeyError ignored int abc

Python compares:

  • Raised exception → ValueError
  • except ValueError → Match ✅ — handler runs
  • except 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.

MahiDev student portal ValueError TypeError IndexError KeyError
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:

python
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

text
ValueError ValueError
ZeroDivisionError ZeroDivisionError
TypeError TypeError
IndexError IndexError
KeyError KeyError

Why does every line print? Because each exception is caught inside the loop, allowing the program to continue instead of crashing.


Quick reference sheet

Quick reference built-in exceptions MahiDev
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
  • except must match the correct exception class
  • Custom exceptions are for business rules; built-in exceptions handle universal programming problems
  • Next: try and except Basics — syntax, multiple except blocks, and your first robust programs

Loading playground…

Check your understanding

Built-in exceptions quiz

int("abc") raises:

1 / 10