Skip to content
Kuza Ndoto Academy

Exceptions

Beginner → IntermediateChapter 7 · Page 37 of 564 min readUpdated 15 Nov 2026

An exception is Python's way of saying "something went wrong while running this line". If nobody handles it, the program stops and prints a traceback. Learning to read exceptions is one of the fastest ways to become a confident programmer.

Three kinds of errors

  • Syntax errors happen before your program even starts, because Python can't understand the code. Forgetting the colon in if marks > 50 gives SyntaxError: expected ':'.
  • Exceptions (runtime errors) happen while the program runs: dividing by zero, opening a missing file or converting "abc" to a number.
  • Logic errors don't crash anything; the program simply gives the wrong answer, such as adding when you meant to multiply. Only testing reveals them.

This page is about the second kind.

Reading a traceback

def average(marks):
    return sum(marks) / len(marks)

print(average([80, 90]))
print(average([]))
85.0 Traceback (most recent call last): File "marks.py", line 5, in <module> print(average([])) File "marks.py", line 2, in average return sum(marks) / len(marks) ZeroDivisionError: division by zero

Read a traceback from the bottom up:

  1. The last line names the exception type (ZeroDivisionError) and a message (division by zero).
  2. The lines above show the chain of calls, ending with the line that actually failed (line 2, inside average).
  3. Higher up you see where that function was called from (line 5, at the top level of the file, shown as <module>).

The first call worked and printed 85.0; the second passed an empty list, so len(marks) was 0.

Note

Python 3.11 and later also print ~ and ^ markers under the exact part of a line that failed. We've left them out of the tracebacks on this page to keep them short, so your screen will show a few extra lines.

Common built-in exceptions

ExceptionExample that causes itMessage
ZeroDivisionError10 / 0division by zero
ValueErrorint("abc")invalid literal for int() with base 10: 'abc'
TypeError"Age: " + 21can only concatenate str (not "int") to str
NameErrorUsing a variable that was never createdname '...' is not defined
IndexError[1, 2, 3][5]list index out of range
KeyError{"name": "Ali"}["phone"]'phone'
AttributeErrorCalling a method a type doesn't have, e.g. [1, 2].push(3)'list' object has no attribute 'push'
FileNotFoundErroropen("missing.txt")[Errno 2] No such file or directory: 'missing.txt'
ModuleNotFoundErrorimport requets (typo)No module named 'requets'

The type tells you the category of problem; the message tells you the specifics. A ValueError means the type was right but the value wasn't acceptable (text that isn't a number). A TypeError means the type itself was wrong (adding text to a number).

Tip

Recent Python versions often add a helpful hint to NameError and AttributeError messages, such as Did you mean: 'total'?, when you've made a small typo. Read the whole last line.

Exceptions are objects

Every exception is an object created from a class. When you catch one, you can inspect its type and message:

try:
    int("abc")
except ValueError as error:
    print(type(error).__name__)
    print(error)
    print(error.args)
ValueError invalid literal for int() with base 10: 'abc' ("invalid literal for int() with base 10: 'abc'",)

The exception hierarchy

Exception classes are arranged in a family tree. Catching a parent class also catches all of its children. A simplified part of the tree looks like this:

BaseException
 +-- KeyboardInterrupt        (user pressed Ctrl+C)
 +-- SystemExit               (sys.exit() was called)
 +-- Exception                (almost everything you'll handle)
      +-- ArithmeticError
      |    +-- ZeroDivisionError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- OSError
      |    +-- FileNotFoundError
      |    +-- PermissionError
      +-- TypeError
      +-- ValueError
print(issubclass(ZeroDivisionError, ArithmeticError))
print(issubclass(KeyError, LookupError))
print(issubclass(FileNotFoundError, OSError))
print(issubclass(ValueError, Exception))
True True True True

This matters when you handle errors: catching LookupError handles both missing list positions and missing dictionary keys. Your own custom exceptions should inherit from Exception, as you'll see in Raising Exceptions.

BaseException KeyboardInterrupt SystemExit Exception ArithmeticError LookupError OSError TypeError ValueError ZeroDivisionError IndexError KeyError FileNotFoundError PermissionError
Figure 1. A simplified slice of the exception family tree. Catching a box also catches everything below it, so except LookupError handles both IndexError and KeyError.

Why programs crash, and how to avoid it

An exception travels back up through the functions that were called until something handles it. If it reaches the top of the program unhandled, Python prints the traceback and exits. You have two main tools:

  • Prevent it: check conditions first, for example if marks: before dividing by len(marks), or use dict.get() for keys that may be missing.
  • Handle it: wrap risky code in try/except so the program can recover. That's the subject of the next page, Try, Except & Finally.
def average(marks):
    if not marks:
        return 0
    return sum(marks) / len(marks)

print(average([]))
print(average([70, 80, 95]))
0 81.66666666666667
Common mistake

Don't panic at a long traceback or start changing random lines. Read the last line first, then find the lowest line in the traceback that points to your file. That's almost always where the fix belongs. Searching the exact last line online also works well.

Key points

  • Exceptions are runtime errors; unhandled ones stop the program with a traceback.
  • Read tracebacks bottom up: the type and message first, then the failing line.
  • Know the common types: ValueError, TypeError, KeyError, IndexError, ZeroDivisionError, FileNotFoundError.
  • Exceptions form a hierarchy; catching a parent catches its children.
Up next · Files & ErrorsTry, Except & FinallyHandle errors gracefully.
→

Tip: use the ← and → keys to move between pages.