Python Built-in Exceptions

Python has a wide variety of built-in exceptions that are used to handle errors and other exceptional conditions. These exceptions can be raised by Python itself or manually triggered in your code using the raise statement. Here is a list of the most common built-in exceptions in Python, along with their descriptions and examples:

Common Built-in Exceptions

  1. BaseException
    • The base class for all exceptions in Python. All other built-in exceptions are derived from this class.
    • You usually don’t raise BaseException directly, but you catch it when you want to handle any exception.
    try:
        pass
    except BaseException as e:
        print("An exception occurred:", e)
    
  2. Exception
    • The base class for most exceptions in Python. Almost all built-in exceptions derive from this class, except for system-exiting exceptions such as SystemExit, KeyboardInterrupt, and GeneratorExit.
    • Typically used as a catch-all in exception handling.
    try:
        pass
    except Exception as e:
        print("An exception occurred:", e)
    
  3. ArithmeticError
    • The base class for errors related to arithmetic operations.
    • Subclasses include ZeroDivisionError, OverflowError, and FloatingPointError.
  4. ZeroDivisionError
    • Raised when a division or modulo operation is attempted with zero as the divisor.
    • Example:
    try:
        x = 10 / 0
    except ZeroDivisionError:
        print("Cannot divide by zero")
    
  5. OverflowError
    • Raised when the result of an arithmetic operation is too large to be expressed within the allowed range.
    • Example:
    import math
    try:
        print(math.exp(1000))  # This will raise an OverflowError
    except OverflowError:
        print("Number too large")
    
  6. FloatingPointError
    • Raised when a floating-point operation fails.
    • Example:
    # FloatingPointError is rarely raised, it often happens in hardware-dependent conditions.
    
  7. IndexError
    • Raised when trying to access an index that is out of range in a sequence (e.g., list, tuple).
    • Example:
    my_list = [1, 2, 3]
    try:
        print(my_list[5])
    except IndexError:
        print("Index out of range")
    
  8. KeyError
    • Raised when trying to access a key in a dictionary that does not exist.
    • Example:
    my_dict = {"name": "Alice"}
    try:
        print(my_dict["age"])
    except KeyError:
        print("Key not found")
    
  9. ValueError
    • Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value.
    • Example:
    try:
        x = int("abc")  # Trying to convert a non-numeric string to an integer
    except ValueError:
        print("Invalid value")
    
  10. TypeError
    • Raised when an operation or function is applied to an object of inappropriate type.
    • Example:
    try:
        x = "abc" + 5  # You cannot add a string and an integer
    except TypeError:
        print("Incompatible types")
    
  11. NameError
    • Raised when a local or global name is not found.
    • Example:
    try:
        print(unknown_variable)
    except NameError:
        print("Variable not defined")
    
  12. AttributeError
    • Raised when an attribute reference or assignment fails.
    • Example:
    class MyClass:
        pass
    
    my_obj = MyClass()
    try:
        my_obj.some_attribute
    except AttributeError:
        print("Attribute not found")
    
  13. ImportError
    • Raised when an import statement fails to import a module or a specific name from a module.
    • Example:
    try:
        import non_existent_module
    except ImportError:
        print("Module not found")
    
  14. ModuleNotFoundError
    • A subclass of ImportError, raised when a module could not be found.
    • Example:
    try:
        import non_existent_module
    except ModuleNotFoundError:
        print("Module not found")
    
  15. StopIteration
    • Raised by the next() function to indicate that there are no further items in an iterator.
    • Example:
    my_list = [1, 2, 3]
    iterator = iter(my_list)
    
    try:
        while True:
            print(next(iterator))
    except StopIteration:
        print("End of iterator")
    
  16. StopAsyncIteration
    • Raised when an asynchronous iterator’s __anext__ method signals that there are no more items.
    • Example:
    async def my_async_gen():
        yield 1
        yield 2
    
    async_gen = my_async_gen()
    try:
        await async_gen.__anext__()
    except StopAsyncIteration:
        print("End of async iterator")
    
  17. IOError
    • Raised when an I/O operation (e.g., file reading/writing) fails. In Python 3, it’s an alias of OSError.
    • Example:
    try:
        with open("non_existent_file.txt", "r") as file:
            pass
    except IOError:
        print("I/O error occurred")
    
  18. OSError
    • Raised when a system-related error occurs (e.g., file not found, disk full).
    • Example:
    try:
        with open("non_existent_file.txt", "r") as file:
            pass
    except OSError:
        print("OS error occurred")
    
  19. FileNotFoundError
    • Raised when trying to open a file that does not exist. It’s a subclass of OSError.
    • Example:
    try:
        open("non_existent_file.txt", "r")
    except FileNotFoundError:
        print("File not found")
    
  20. EOFError
    • Raised when the input() function hits an end-of-file condition (EOF) without reading any data.
    • Example:
    try:
        input("Enter something: ")
    except EOFError:
        print("End of file reached")
    
  21. RuntimeError
    • Raised when an error occurs that does not fall under any other specific category.
    • Example:
    def recursive():
        return recursive()
    
    try:
        recursive()
    except RuntimeError:
        print("Runtime error occurred")
    
  22. RecursionError
    • A subclass of RuntimeError, raised when the maximum recursion depth is exceeded.
    • Example:
    try:
        def recursive():
            return recursive()
        recursive()
    except RecursionError:
        print("Recursion depth exceeded")
    
  23. SyntaxError
    • Raised when there is an error in Python syntax.
    • Example:
    try:
        eval("x === x")
    except SyntaxError:
        print("Syntax error")
    
  24. IndentationError
    • Raised when the indentation is incorrect (e.g., unexpected indentation or inconsistent indentation).
    • Example:
    # Inconsistent indentation would cause an IndentationError.
    
  25. KeyboardInterrupt
    • Raised when the user interrupts program execution, usually by pressing Ctrl+C.
    • Example:
    try:
        while True:
            pass
    except KeyboardInterrupt:
        print("Execution interrupted by user")
    
  26. SystemExit
    • Raised when the sys.exit() function is called, signaling that the program should terminate.
    • Example:
    import sys
    try:
        sys.exit()
    except SystemExit:
        print("SystemExit called")
    

Summary:

  • General: BaseException, Exception, RuntimeError, RecursionError, SystemExit, KeyboardInterrupt
  • Arithmetic: ArithmeticError, ZeroDivisionError, OverflowError, FloatingPointError
  • Lookup: IndexError, KeyError
  • Value/Type: ValueError, TypeError, AttributeError, NameError
  • I/O: IOError, OSError, FileNotFoundError, EOFError
  • Iteration: StopIteration, StopAsyncIteration
  • Importing: ImportError, ModuleNotFoundError
  • Syntax: SyntaxError, IndentationError

These built-in exceptions are essential for handling various types of errors and ensuring your Python programs run smoothly under all conditions.

Leave a Reply 0

Your email address will not be published. Required fields are marked *