Course topics

By WebNest Studio Engineering Team

Python Tutorial

Python Built-in Exceptions Reference

Python raises specific built-in exceptions for different problems, organised in a class hierarchy under BaseException. Recognising them quickly — and knowing which one to catch or raise — makes debugging faster and error handling more precise.

This reference lists the exceptions you will meet most often, explains what causes each one, and shows code that triggers and handles them.

Why it matters

The name of an exception tells you what kind of mistake happened before you read anything else: KeyError means a missing dictionary key, TypeError the wrong kind of value. Knowing the common ones and how they are related lets you read a traceback quickly and catch exactly the right class.

The Hierarchy

BaseException is the root. Directly under it are SystemExit, KeyboardInterrupt and GeneratorExit, which normal code should not catch. Everything else derives from Exception, grouped into families such as ArithmeticError (ZeroDivisionError, OverflowError), LookupError (IndexError, KeyError) and OSError (FileNotFoundError, PermissionError, TimeoutError, ConnectionError...). Catching a family catches all its members.

Most Common Exceptions

The ones you will see daily:

  • SyntaxError / IndentationError — code cannot be parsed.
  • NameError — a name is not defined (typo or missing import).
  • TypeError — operation on the wrong type, or wrong number of arguments.
  • ValueError — right type, invalid value (int("abc")).
  • AttributeError — object has no such attribute or method.
  • IndexError — sequence index out of range; KeyError — missing dict key.
  • ZeroDivisionError, OverflowError — arithmetic problems.
  • FileNotFoundError, PermissionError, IsADirectoryError — file system problems.
  • ImportError / ModuleNotFoundError — import failures.
  • StopIteration — iterator exhausted; RecursionError — too deep recursion.
  • AssertionError, NotImplementedError, RuntimeError, MemoryError, UnicodeDecodeError.

Reading Tracebacks

Read a traceback from the bottom up: the last line shows the exception type and message; the lines above show the chain of calls, with the most recent call last. Modern Python versions underline the exact failing expression and suggest fixes such as "Did you mean: 'append'?".

Examples

Triggering and naming common exceptions

Python
import math

tests = [
    lambda: undefined_variable,
    lambda: "5" + 5,
    lambda: int("abc"),
    lambda: [1, 2, 3][10],
    lambda: {"a": 1}["b"],
    lambda: 10 / 0,
    lambda: "text".push("x"),
    lambda: open("missing_file.txt"),
    lambda: __import__("not_a_real_module"),
    lambda: next(iter([])),
    lambda: math.exp(1000),
    lambda: b"\xff".decode("utf-8"),
]
for test in tests:
    try:
        test()
    except Exception as e:
        # OSError numbers differ between platforms, so show only the message
        message = f"{e.strerror}: {e.filename!r}" if isinstance(e, OSError) else e
        print(f"{type(e).__name__:<20} {message}")
Output
NameError            name 'undefined_variable' is not defined
TypeError            can only concatenate str (not "int") to str
ValueError           invalid literal for int() with base 10: 'abc'
IndexError           list index out of range
KeyError             'b'
ZeroDivisionError    division by zero
AttributeError       'str' object has no attribute 'push'
FileNotFoundError    No such file or directory: 'missing_file.txt'
ModuleNotFoundError  No module named 'not_a_real_module'
StopIteration
OverflowError        math range error
UnicodeDecodeError   'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

Catching exception families and inspecting the hierarchy

Python
def safe_get(container, key):
    try:
        return container[key]
    except LookupError as e:              # covers IndexError and KeyError
        return f"missing ({type(e).__name__})"

print(safe_get([1, 2], 5), safe_get({"a": 1}, "z"), safe_get("abc", 1))

for exc in (IndexError, KeyError, FileNotFoundError, ZeroDivisionError, KeyboardInterrupt):
    print(exc.__name__, "->", " > ".join(c.__name__ for c in exc.__mro__[1:-1]))
Output
missing (IndexError) missing (KeyError) b
IndexError -> LookupError > Exception > BaseException
KeyError -> LookupError > Exception > BaseException
FileNotFoundError -> OSError > Exception > BaseException
ZeroDivisionError -> ArithmeticError > Exception > BaseException
KeyboardInterrupt -> BaseException

Printing a full traceback without crashing

Python
import traceback

def level_two():
    return {"user": None}["user"]["name"]

def level_one():
    return level_two()

try:
    level_one()
except TypeError:
    lines = traceback.format_exc().strip().splitlines()
    print(lines[0])
    print(lines[-1])
Output
Traceback (most recent call last):
TypeError: 'NoneType' object is not subscriptable

Common Mistakes

  • Catching BaseException or using bare except, which traps Ctrl+C and sys.exit().
  • Reading tracebacks from the top instead of the last line.
  • Catching Exception everywhere, hiding the specific type you should handle.
  • Confusing TypeError (wrong type) with ValueError (right type, bad value).

Exercise

Each function in the list fails with a different built-in exception. Call each one, catch the exception, and print the name of its class.

Expected output: ValueError, IndexError, KeyError, ZeroDivisionError, TypeError (one per line)

Python · starter code
operations = [
    lambda: int("x"),
    lambda: [1][5],
    lambda: {}["k"],
    lambda: 1 / 0,
    lambda: "a" + 1,
]

for operation in operations:
    # TODO: call the operation, catch the exception and print its class name
    pass
Show hints
  • except Exception as error: catches all five and gives you the exception object.
  • The class name is type(error).__name__.
Show solution
Python · solution
operations = [
    lambda: int("x"),
    lambda: [1][5],
    lambda: {}["k"],
    lambda: 1 / 0,
    lambda: "a" + 1,
]

for operation in operations:
    try:
        operation()
    except Exception as error:
        print(type(error).__name__)

Quick quiz

1. Which exception is raised by len(5)?

  • A. ValueError
  • B. AttributeError
  • C. TypeError
  • D. IndexError
Show answer

C. TypeError means the operation does not apply to a value of that type.

2. Which class is the common parent of KeyError and IndexError?

  • A. ValueError
  • B. RuntimeError
  • C. ArithmeticError
  • D. LookupError
Show answer

D. Catching LookupError handles a failed lookup in either a dictionary or a sequence.

3. In a traceback, where is the line that raised the exception?

  • A. At the bottom, just above the error message
  • B. At the top
  • C. It is not shown
  • D. In the middle
Show answer

A. A traceback lists the calls from the outermost to the innermost, so it is read from the bottom up.

Interview questions

What is the difference between Exception and BaseException?

Show answer

BaseException is the root of the whole hierarchy. Directly under it are SystemExit, KeyboardInterrupt and GeneratorExit, which signal that the program is being asked to stop, and Exception, the parent of all ordinary errors. Code should catch Exception or something more specific, so that Ctrl+C and sys.exit() still work.

What is the difference between ValueError and TypeError?

Show answer

TypeError is raised when a value is of the wrong type for the operation, as in "a" + 1. ValueError is raised when the type is acceptable but the value is not, as in int("abc"), where a string is allowed but this particular string is not a number.

Key Points to Remember

  • All normal exceptions derive from Exception; SystemExit and KeyboardInterrupt do not.
  • Families: ArithmeticError, LookupError, OSError — catch a family to handle all members.
  • Know the common ones: NameError, TypeError, ValueError, AttributeError, IndexError, KeyError, FileNotFoundError...
  • Read tracebacks bottom-up; the traceback module formats them in code.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering