Python Built-in Exceptions: Full Guide with Examples

Last updated 4 weeks ago | 90 views 75     5

Tags:- Python

Python has a rich set of built-in exceptions designed to handle various types of runtime errors. These exceptions help you detect and respond to unexpected events during program execution.

In this guide, you'll learn:

  • What built-in exceptions are

  • A complete list of Python built-in exceptions

  • An example for each exception


What Are Built-in Exceptions?

Built-in exceptions are predefined error classes in Python. They’re raised automatically (or manually using raise) when an error occurs during the execution of a program.


⚠️ Categories of Exceptions

Python exceptions can be broadly classified as:

  • BaseException (base class)

    • SystemExit, KeyboardInterrupt, etc.

  • Exception (most user-defined errors derive from here)

    • ArithmeticError, LookupError, etc.


List of Python Built-in Exceptions (with Examples)

Below is a list of the most commonly used built-in exceptions in Python, along with a short code example for each.


✅ 1. ArithmeticError

Base class for arithmetic errors.

try:
    x = 1 / 0
except ArithmeticError as e:
    print("Arithmetic error:", e)

✅ 2. ZeroDivisionError

Division by zero.

try:
    result = 5 / 0
except ZeroDivisionError as e:
    print("Cannot divide by zero:", e)

✅ 3. OverflowError

Math result too large to represent.

try:
    import math
    print(math.exp(1000))
except OverflowError as e:
    print("Overflow error:", e)

✅ 4. FloatingPointError

Rare; occurs in floating-point calculations.

import numpy as np
np.seterr(all='raise')
try:
    np.divide(1.0, 0.0)
except FloatingPointError as e:
    print("Floating point error:", e)

✅ 5. AssertionError

Raised by assert statement.

try:
    assert 2 + 2 == 5
except AssertionError as e:
    print("Assertion failed:", e)

✅ 6. AttributeError

Accessing an attribute that doesn’t exist.

try:
    "hello".fake_method()
except AttributeError as e:
    print("Attribute error:", e)

✅ 7. EOFError

Input ends unexpectedly.

try:
    input("Press Ctrl+D to raise EOFError: ")
except EOFError as e:
    print("EOF Error:", e)

✅ 8. ImportError

Import fails.

try:
    import non_existing_module
except ImportError as e:
    print("Import error:", e)

✅ 9. ModuleNotFoundError

Subclass of ImportError.

try:
    import fake_module
except ModuleNotFoundError as e:
    print("Module not found:", e)

✅ 10. IndexError

List index out of range.

try:
    lst = [1, 2, 3]
    print(lst[10])
except IndexError as e:
    print("Index error:", e)

✅ 11. KeyError

Accessing a non-existent key in a dictionary.

try:
    d = {"name": "Alice"}
    print(d["age"])
except KeyError as e:
    print("Key error:", e)

✅ 12. KeyboardInterrupt

Interrupt with Ctrl+C.

try:
    while True:
        pass
except KeyboardInterrupt:
    print("Keyboard Interrupt")

✅ 13. MemoryError

Out of memory.

try:
    a = ' ' * (10**10)
except MemoryError as e:
    print("Memory error:", e)

✅ 14. NameError

Using an undefined variable.

try:
    print(x)
except NameError as e:
    print("Name error:", e)

✅ 15. UnboundLocalError

Local variable referenced before assignment.

def func():
    try:
        print(x)
        x = 10
    except UnboundLocalError as e:
        print("Unbound local error:", e)
func()

✅ 16. OSError

Base class for OS-related errors.

try:
    open('/path/that/does/not/exist.txt')
except OSError as e:
    print("OS error:", e)

✅ 17. FileNotFoundError

File doesn't exist.

try:
    open("nofile.txt")
except FileNotFoundError as e:
    print("File not found:", e)

✅ 18. PermissionError

Lack of permissions.

try:
    open("/etc/shadow", "r")
except PermissionError as e:
    print("Permission denied:", e)

✅ 19. IsADirectoryError

Attempting to open a directory as a file.

try:
    open(".")  # Current directory
except IsADirectoryError as e:
    print("Is a directory:", e)

✅ 20. NotADirectoryError

Path component is not a directory.

try:
    import os
    os.listdir("file.txt/folder")
except NotADirectoryError as e:
    print("Not a directory:", e)

✅ 21. TypeError

Wrong data type used.

try:
    print("2" + 2)
except TypeError as e:
    print("Type error:", e)

✅ 22. ValueError

Right type, but wrong value.

try:
    int("abc")
except ValueError as e:
    print("Value error:", e)

✅ 23. RuntimeError

Generic error not covered by other exceptions.

try:
    raise RuntimeError("Something went wrong")
except RuntimeError as e:
    print("Runtime error:", e)

✅ 24. RecursionError

Too much recursion.

def recurse():
    return recurse()
try:
    recurse()
except RecursionError as e:
    print("Recursion error:", e)

✅ 25. StopIteration

Iterator is exhausted.

try:
    it = iter([1])
    next(it)
    next(it)
except StopIteration:
    print("StopIteration raised")

✅ 26. StopAsyncIteration

Async iterator is exhausted.

class AsyncCounter:
    async def __anext__(self):
        raise StopAsyncIteration

# Typically used with `async for`

✅ 27. IndentationError

Incorrect indentation.

# Cannot be caught in runtime; it is a syntax error.
# Example (invalid code):
# def func():
# print("No indent")

✅ 28. TabError

Mixing tabs and spaces.

(Syntax-level error — not catchable at runtime.)


✅ 29. SyntaxError

Invalid Python syntax.

try:
    eval("x === y")
except SyntaxError as e:
    print("Syntax error:", e)

✅ 30. SystemExit

Raised by sys.exit().

import sys
try:
    sys.exit()
except SystemExit:
    print("Exiting...")

✅ 31. BlockingIOError, ChildProcessError, ConnectionError, BrokenPipeError, TimeoutError, etc.

These are less common and are used for system-level and network operations.


Summary Table

Exception Description
ZeroDivisionError Division by zero
TypeError Invalid type
ValueError Valid type, wrong value
KeyError Dict key not found
IndexError Index out of range
ImportError, ModuleNotFoundError Import failures
AttributeError Missing attribute
FileNotFoundError File does not exist
OSError, PermissionError OS-related errors
SyntaxError, IndentationError Syntax problems (at compile-time)
RuntimeError, RecursionError Runtime issues
StopIteration, StopAsyncIteration Iterator exhausted
SystemExit, KeyboardInterrupt System-related events

✅ Best Practices

  • Use try / except blocks to handle exceptions gracefully.

  • Use specific exceptions when possible.

  • Log the error messages for debugging.

  • Avoid catching BaseException unless absolutely necessary.


Final Thoughts

Understanding Python’s built-in exceptions helps you write robust, fault-tolerant programs. Always handle exceptions responsibly and test edge cases in your applications.