What are the built-in exception classes in Python?

Python provides a comprehensive set of built-in exception classes for handling various error conditions. These exceptions are derived from the base class BaseException. Below is a categorized list of the most common built-in exceptions in Python:


1. Base Classes

  • BaseException: The base class for all built-in exceptions. You usually do not handle this directly.
  • Exception: The base class for all exceptions that are not system-exiting. Most user-defined exceptions inherit from this.

2. SystemExit and Environment Exceptions

  • SystemExit: Raised when sys.exit() is called to exit the program.
  • KeyboardInterrupt: Raised when the user interrupts program execution (e.g., pressing Ctrl+C).
  • GeneratorExit: Raised when a generator’s close() method is called.

3. Standard Exceptions

Errors Related to Syntax and Logic:

  • SyntaxError: Raised when the parser encounters a syntax error.
  • IndentationError: Raised when there is incorrect indentation.
    • TabError: Raised when indentation consists of inconsistent tabs and spaces.

Errors Related to Value, Type, and Index:

  • TypeError: Raised when an operation is performed on an inappropriate type.
  • ValueError: Raised when a function receives an argument of the correct type but inappropriate value.
  • IndexError: Raised when a sequence index is out of range.
  • KeyError: Raised when a key is not found in a dictionary.

Errors Related to Numbers:

  • ZeroDivisionError: Raised when attempting to divide by zero.
  • OverflowError: Raised when a mathematical operation exceeds the limits of the data type.
  • FloatingPointError: Raised for floating-point operations (rare).

Errors Related to Iteration:

  • StopIteration: Raised by an iterator to signal that there are no further items.
  • StopAsyncIteration: Raised by asynchronous iterators to signal the end of iteration.

Errors Related to Importing Modules:

  • ImportError: Raised when an import statement fails.
    • ModuleNotFoundError: A subclass of ImportError, raised when a module cannot be found.

Errors Related to File and Input/Output:

  • FileNotFoundError: Raised when a file or directory is requested but not found.
  • PermissionError: Raised when an operation lacks the necessary permissions.
  • IOError: Raised for I/O operations (e.g., file not found, disk full).
  • EOFError: Raised when the input() function hits end-of-file.

Errors Related to Lookups and Attribute Access:

  • AttributeError: Raised when an invalid attribute is accessed.
  • NameError: Raised when a local or global name is not found.
    • UnboundLocalError: A subclass of NameError, raised for references to uninitialized local variables.

Errors Related to Assertions and Arithmetic:

  • AssertionError: Raised when an assert statement fails.
  • ArithmeticError: The base class for all arithmetic errors.
    • FloatingPointError
    • OverflowError
    • ZeroDivisionError

4. Warnings

Warnings are not exceptions but are used to notify developers of potential issues.

  • Warning: The base class for all warnings.
    • UserWarning
    • DeprecationWarning
    • SyntaxWarning
    • RuntimeWarning
    • FutureWarning

5. OS-Related Exceptions

  • OSError: Raised for system-related errors (e.g., file not found, disk full).
    • FileExistsError: Raised when a file or directory already exists.
    • IsADirectoryError: Raised when a directory operation is expected but a file is given.
    • NotADirectoryError: Raised when a file operation is expected but a directory is given.
    • PermissionError
    • FileNotFoundError

6. Specific Runtime and Execution Errors

  • RuntimeError: Raised when an error doesn’t fit into any other category.
  • NotImplementedError: Raised when an abstract method needs to be overridden by a subclass.
  • RecursionError: Raised when the maximum recursion depth is exceeded.

7. Memory-Related Errors

  • MemoryError: Raised when an operation runs out of memory.
  • BufferError: Raised when performing an operation on a buffer that the operation cannot handle.

8. Connection and Network Errors

  • ConnectionError: The base class for network-related exceptions.
    • ConnectionAbortedError
    • ConnectionRefusedError
    • ConnectionResetError
  • TimeoutError: Raised when a connection times out.

9. Custom and User-Defined Exceptions

Python allows developers to create custom exceptions by subclassing Exception.

Example:

class CustomError(Exception):
    pass

try:
    raise CustomError("Something went wrong!")
except CustomError as e:
    print(e)

Hierarchy of Built-In Exceptions

All exceptions are part of the following hierarchy:

BaseException
 ├── SystemExit
 ├── KeyboardInterrupt
 ├── GeneratorExit
 └── Exception
      ├── ArithmeticError
      ├── AttributeError
      ├── EOFError
      ├── ImportError
      ├── IndexError
      ├── KeyError
      ├── NameError
      ├── OSError
      ├── RuntimeError
      ├── TypeError
      ├── ValueError
      ├── ...

These exceptions cover a wide range of scenarios, helping developers handle errors effectively in Python programs.