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.
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
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}")
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
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]))
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
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])
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).
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 the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.