Skip to content

Module 12 · Exception Handling — topic 3 of 11

Common exceptions

The built-in exceptions you'll meet most: ValueError, TypeError, NameError, IndexError, KeyError, AttributeError, ZeroDivisionError, FileNotFoundError, ModuleNotFoundError — what causes each and how they are grouped.

Beginner 10 min read·Lesson 185 of 306 in Python Programming

Learning objectives

  • Recognise the most common built-in exceptions
  • Know a typical cause of each
  • Use base classes such as LookupError and OSError

Definition

Python defines a hierarchy of built-in exception classes, each describing a category of error. Knowing the common ones lets you recognise problems quickly and catch exactly the errors you expect.

Introduction

Most errors you'll see in practice come from a short list of exception types. Each name tells you what kind of mistake happened.

Why it matters

Recognising the exception type is the first step in debugging, and catching the right type keeps your handlers precise.

Detailed explanation

ValueError: the type is right but the value is not — int('abc'), math.sqrt(-1).

TypeError: an operation is applied to the wrong type — 'a' + 1, len(5), calling a function with wrong arguments.

NameError: a name isn't defined — usually a typo or a variable used before assignment.

IndexError: a sequence index is out of range. KeyError: a dictionary key is missing. Both derive from LookupError.

AttributeError: an object has no such attribute or method — often calling a method on None.

ZeroDivisionError (an ArithmeticError): dividing or taking a modulo by zero.

FileNotFoundError, PermissionError and IsADirectoryError derive from OSError. ModuleNotFoundError (a subclass of ImportError) means an import failed.

Catching a base class handles all its subclasses: except LookupError catches IndexError and KeyError.

Syntax

Python
try:
value = data[key]
except LookupError: # IndexError or KeyError
value = None
  • Each exception type names a kind of error.
  • Base classes group related errors.
  • Catch the most specific type you can handle.

Code examples

Six everyday exceptions

Python
tests = [
lambda: int("abc"),
lambda: [1, 2][5],
lambda: {"a": 1}["b"],
lambda: "a" + 1,
lambda: None.upper(),
lambda: 10 / 0,
]
for t in tests:
try:
t()
except Exception as e:
print(f"{type(e).__name__}: {e}")
Output
ValueError: invalid literal for int() with base 10: 'abc'
IndexError: list index out of range
KeyError: 'b'
TypeError: can only concatenate str (not "int") to str
AttributeError: 'NoneType' object has no attribute 'upper'
ZeroDivisionError: division by zero

File and import errors

Python
try:
open("no_such_file.txt")
except FileNotFoundError as e:
print(type(e).__name__, e.errno, e.filename)
try:
import no_such_module
except ModuleNotFoundError as e:
print(type(e).__name__, e.name)
Output
FileNotFoundError 2 no_such_file.txt
ModuleNotFoundError no_such_module

More examples

Catching a family with a base class

Python
def get(container, key):
try:
return container[key]
except LookupError as e:
return f"missing ({type(e).__name__})"
print(get([10, 20], 1), get([10, 20], 9), get({"x": 1}, "y"))
print(issubclass(IndexError, LookupError),
issubclass(KeyError, LookupError),
issubclass(FileNotFoundError, OSError))
Output
20 missing (IndexError) missing (KeyError)
True True True

Step-by-step explanation

  • One handler for LookupError works for both lists (IndexError) and dictionaries (KeyError).
  • type(e).__name__ still reveals which specific exception occurred.
  • issubclass confirms the relationships in the hierarchy.

Expected output

Running “Catching a family with a base class” prints exactly:

TextOutput
20 missing (IndexError) missing (KeyError)
True True True

Practical applications

  • ValueError for invalid user input in forms.
  • FileNotFoundError when a configuration file is missing.

Best practices

  • Learn the meaning of each common exception.
  • Catch specific types or meaningful base classes.
  • Use the message and type in your error reports.

Common mistakes

Catching TypeError to hide a bug

Avoid

try:
total = price + qty
except TypeError:
total = 0

Prefer

total = float(price) + int(qty) # convert input deliberately

A TypeError usually means a bug to fix, not a condition to silence.

Important notes

  • The full hierarchy is listed in the Python documentation under 'Built-in Exceptions'.

Key takeaways

  • ValueError: bad value; TypeError: wrong type.
  • IndexError and KeyError are LookupErrors.
  • File errors are OSErrors.

Try it yourself

  1. 1
    Write one line that raises each of AttributeError, NameError and KeyError, and catch them.
  2. 2
    Explain why int('3.5') raises ValueError but int(None) raises TypeError.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhich exception does {"a": 1}["b"] raise?
Practise this topic