Sobes.tech
Junior

What classes of exceptions exist in Python?

sobes.tech AI

Answer from AI

In Python, there is a hierarchy of exception classes, where most exceptions are derived from the Exception class. Some key classes include:

  • BaseException: The base class for all exceptions. It is not recommended to handle it directly, except in very rare cases.
  • Exception: The base class for all non-system exceptions, which are usually caught in programs.
  • ArithmeticError: The base class for exceptions related to arithmetic operations. It includes:
    • FloatingPointError: Exception for floating point operation failures.
    • OverflowError: Exception when a number exceeds the allowable range.
    • ZeroDivisionError: Exception for division by zero.
  • AssertionError: Exception when an assert statement fails.
  • AttributeError: Exception when trying to access or call a non-existent attribute or method.
    # Example AttributeError
    class MyClass:
        pass
    
    obj = MyClass()
    # print(obj.non_existent_attribute) # Will raise AttributeError
    
  • EOFError: Exception when the end of a file is reached without reading data.
  • ImportError: The base class for import-related exceptions. It includes:
    • ModuleNotFoundError: Exception when a module cannot be found.
  • IndexError: Exception when an index is out of range in a sequence.
    # Example IndexError
    my_list = [1, 2, 3]
    # print(my_list[3]) # Will raise IndexError
    
  • KeyError: Exception when accessing a non-existent key in a dictionary.
    # Example KeyError
    my_dict = {"a": 1, "b": 2}
    # print(my_dict["c"]) # Will raise KeyError
    
  • KeyboardInterrupt: Exception when the user interrupts the program (usually Ctrl+C).
  • MemoryError: Exception when available memory is exhausted.
  • NameError: Exception when using an undefined variable.
    # Example NameError
    # print(undefined_variable) # Will raise NameError
    
  • OSError: The base class for operating system-related exceptions. It includes:
    • FileNotFoundError: Exception when trying to access a non-existent file or directory.
    • IsADirectoryError: Exception when performing a file operation on a directory.
    • NotADirectoryError: Exception when performing a file operation on a non-directory.
    • PermissionError: Exception when lacking access rights.
  • RuntimeError: Exception that occurs when a class does not fall under any other exception category.
  • SyntaxError: Exception when a syntax error is detected in the code.
  • SystemError: Exception when an internal interpreter error is detected.
  • TypeError: Exception when an operation or function is applied to an object of inappropriate type.
    # Example TypeError
    # print(1 + "2") # Will raise TypeError
    
  • ValueError: Exception when a function receives an argument of the correct type but inappropriate value.
    # Example ValueError
    # int("abc") # Will raise ValueError
    
  • ZeroDivisionError (already mentioned in ArithmeticError)

Some exceptions are subclasses of others, forming a hierarchy. For example, ModuleNotFoundError is a subclass of ImportError.

Part of the hierarchy:

BaseException
 ├── Exception
 │   ├── ArithmeticError
 │   │   ├── FloatingPointError
 │   │   ├── OverflowError
 │   │   └── ZeroDivisionError
 │   ├── AssertionError
 │   ├── AttributeError
 │   ├── EOFError
 │   ├── ImportError
 │   │   └── ModuleNotFoundError
 │   ├── IndexError
 │   ├── KeyError
 │   ├── MemoryError
 │   ├── NameError
 │   ├── OSError
 │   │   ├── FileNotFoundError
 │   │   ├── IsADirectoryError
 │   │   ├── NotADirectoryError
 │   │   └── PermissionError
 │   ├── RuntimeError
 │   ├── SyntaxError
 │   ├── TypeError
 │   └── ValueError
 └── KeyboardInterrupt

This is not an exhaustive list but includes the most common exceptions.

When handling exceptions, it is recommended to catch more specific exceptions before more general ones to ensure more precise error handling.