Summary of Common Python Exceptions

Time: Column:Python views:212

Exceptions in Python is a broad topic, as it includes numerous built-in exception types that can handle a variety of runtime errors. Below is a list of some common Python exception categories and their uses:

1. Built-in Exceptions

  • Exception: The base class for almost all other error classes.

  • AttributeError: Raised when an attempt is made to access an attribute of an object that does not exist.

  • IOError: Raised when input/output operations (e.g., opening or reading a file) fail.

  • ImportError: Raised when an import statement cannot find or load a module.

  • IndexError: Raised when a sequence index is out of range.

  • KeyError: Raised when a dictionary lookup fails for a non-existent key.

  • KeyboardInterrupt: Raised when the user interrupts program execution, typically by pressing Ctrl+C.

  • NameError: Raised when a local or global name is not found.

  • OSError: Used for operating system-related failures, such as opening files or executing commands.

  • SyntaxError: Raised when the Python interpreter detects a syntax error.

  • TypeError: Raised when an operation or function is applied to an object of inappropriate type.

  • ValueError: Raised when an operation or function receives an argument of the right type but inappropriate value.

  • ZeroDivisionError: Raised when a division or modulo operation is attempted with zero as the divisor.

2. Warnings

  • Warning: The base class for all warning-related exceptions.

  • DeprecationWarning: Warning about deprecated features.

  • UserWarning: Warning defined by developers.

  • SyntaxWarning: Warning about suspicious syntax.

3. File and I/O Exceptions

  • FileNotFoundError: Raised when attempting to open a file that does not exist (introduced in Python 3).

  • FileExistsError: Raised when trying to create a file or directory that already exists (introduced in Python 3).

  • PermissionError: Raised when attempting to perform an operation without sufficient permissions (introduced in Python 3).

4. Other Specific Exceptions

  • MemoryError: Raised when an operation cannot complete due to insufficient memory.

  • RecursionError: Raised when recursion exceeds the maximum depth limit (introduced in Python 3.5, replacing RuntimeError).

  • StopIteration: Raised when an iterator has no more items to provide.

  • TimeoutError: Raised when a system function does not complete within a specified time.

These are some common types of exceptions in Python. The Python standard library also defines many other exceptions tailored for specific use cases, such as network programming and multithreading. Understanding and properly using these exceptions can help developers write robust, maintainable, and error-resilient programs.