Python’s Built-in Exceptions

Built-in exceptions in Python are predefined error classes that the interpreter uses to handle various error conditions. When something goes wrong during program execution, Python raises (or “throws”) an appropriate exception, which can be “caught” and handled using tryexcept blocks.

Key Concepts

  • Exception Class Hierarchy: All built-in exceptions inherit from BaseException, with most practical exceptions inheriting from its subclass Exception.

  • Raising Exceptions: You can raise exceptions using the raise keyword:

    Python
    raise ValueError("Invalid input")
    

  • Exception Handling: Use tryexcept blocks to catch and handle exceptions gracefully:

    Python
     try:
         result = 10 / 0
     except ZeroDivisionError:
         print("To infinity and beyond...")
    

Python has a structured set of exceptions that cover many error conditions. In your code, you can catch specific errors by name to manage errors more precisely. Below is a list of Python’s built-in exceptions and their purposes:

  • ArithmeticError Serves as the base class for all errors that occur during arithmetic operations.
  • AssertionError Occurs when an assert statement fails.
  • AttributeError Occurs when you attempt to access a method or property that isn’t defined for the object in question.
  • BaseException Serves as the base class for all exceptions.
  • BaseExceptionGroup Allows for managing multiple exceptions that occur simultaneously.
  • BlockingIOError Occurs when an input/output (I/O) operation is blocked.
  • BrokenPipeError Occurs when a process tries to write to a pipe while the other end has been closed.
  • BufferError Occurs when an operation can’t be performed on a buffer due to the current state of the buffer.
  • ChildProcessError Occurs when an operation on a child process fails.
  • ConnectionAbortedError Occurs when a peer unexpectedly closes an established connection.
  • ConnectionError Signals issues related to network connectivity.
  • ConnectionRefusedError Occurs when a connection attempt to a remote server is explicitly refused.
  • ConnectionResetError Occurs when a network connection is forcefully closed by the peer.
  • EOFError Occurs when the built-in input() function hits an end-of-file (EOF) condition without reading any data.
  • Exception Serves as the base class for all built-in exceptions except for system-exiting exceptions.
  • FileExistsError Occurs when an operation attempts to create a file or directory that already exists.
  • FileNotFoundError Occurs when an operation requires a file or directory that doesn’t exist in the specified location.
  • FloatingPointError Indicates an error related to floating-point arithmetic operations.
  • GeneratorExit Occurs when a generator or coroutine is closed.
  • ImportError Occurs when an import statement fails to load a module or a name from a module.
  • IndentationError Occurs when the indentation of your code is incorrect.
  • IndexError Occurs when you try to access an index that is out of range for a sequence, such as a list, tuple, or string.
  • InterruptedError Occurs when a system call is interrupted by an external signal.
  • IOError Is used to handle input/output (I/O) related errors, such as problems reading or writing files.
  • IsADirectoryError Occurs when an operation expected to be performed on a file is attempted on a directory instead.
  • KeyboardInterrupt Occurs when the user interrupts the execution of a program using the keyboard.
  • KeyError Occurs when you try to access a missing key in a dictionary.
  • LookupError Serves as the base class for exceptions raised when a key or index used on a mapping or sequence is invalid.
  • MemoryError Occurs when your program runs out of memory.
  • ModuleNotFoundError Occurs when an import statement fails to locate the specified module.
  • NameError Occurs when you try to use a variable or function name that hasn’t been defined yet.
  • NotADirectoryError Occurs when an operation that is expected to act on a directory is applied to a file.
  • NotImplementedError Signals that a particular method or function hasn’t been implemented yet.
  • OSError Occurs when Python detects a system-related error.
  • OverflowError Occurs when the result of an arithmetic operation is too large to be expressed within the available numeric type’s range.
  • PermissionError Occurs when an operation attempts to access a file or directory without the necessary permissions.
  • RecursionError Occurs when the maximum recursion depth is exceeded.
  • RuntimeError Indicates an error that doesn’t fall into any other category has occurred.
  • StopAsyncIteration Signals the end of an asynchronous iteration.
  • StopIteration Signals the end of an iteration.
  • SyntaxError Occurs when the interpreter encounters a line of code that violates Python’s syntax rules.
  • SystemExit Terminate the Python interpreter.
  • TabError Occurs when you mix tabs and spaces in your code indentation.
  • TimeoutError Occurs when a system function like time.sleep() or another operation times out.
  • TypeError Occurs when an operation or function is applied to an object of inappropriate type.
  • ValueError Occurs when a function or operation receives an argument that has the right type but an inappropriate value.
  • ZeroDivisionError Occurs when you attempt to divide a number by zero, which is mathematically undefined.