Sobes.tech
Junior

What are the features of exception handling in Python?

sobes.tech AI

Answer from AI

Exceptions in Python are events that disrupt the normal flow of program execution. They are objects that represent errors.

Features:

  • Hierarchy of exceptions: All built-in exceptions are classes organized in a hierarchy based on inheritance from the base class BaseException.
    # Example hierarchy
    # BaseException -> Exception -> StandardError -> ...
    #                  Exception -> ArithmeticError -> ZeroDivisionError
    
  • try...except... blocks: The main mechanism for handling exceptions.
    try:
        # Code that might raise an exception
        result = 10 / 0
    except ZeroDivisionError:
        # Handling a specific exception
        print("Division by zero!")
    except Exception as e:
        # Handling other exceptions
        print(f"An error occurred: {e}")
    
  • Multiple except blocks: Allow handling different types of exceptions differently.
    try:
        # Code
        value = int("abc")
    except ValueError:
        print("Invalid number format.")
    except TypeError:
        print("Invalid data type.")
    
  • else block: Executes if the try block completes without exceptions.
    try:
        # Code
        result = 10 / 2
    except ZeroDivisionError:
        print("Division by zero!")
    else:
        print("Operation completed successfully.")
    
  • finally block: Always executes, regardless of whether an exception occurred or not. Used for resource cleanup.
    file = None
    try:
        file = open("myfile.txt", "r")
        # Reading from file
    except FileNotFoundError:
        print("File not found.")
    finally:
        if file:
            file.close() # Guaranteed file closure
    
  • raise operator: Used to explicitly raise an exception.
    def divide(a, b):
        if b == 0:
            raise ZeroDivisionError("Cannot divide by zero")
        return a / b
    
    try:
        divide(10, 0)
    except ZeroDivisionError as e:
        print(f"Error: {e}")
    
  • Custom exceptions: You can create your own exception classes by inheriting from Exception or another existing exception class.
    class CustomError(Exception):
        pass
    
    def process_data(data):
        if not data:
            raise CustomError("Data is empty")
    
    try:
        process_data([])
    except CustomError as e:
        print(f"Error: {e}")
    
  • Handling exceptions with the with context manager: Simplifies working with resources that require explicit closing (e.g., files).
    try:
        with open("myfile.txt", "r") as file:
            # Working with the file
            content = file.read()
    except FileNotFoundError:
        print("File not found.")
    # The file is automatically closed when exiting the 'with' block
    
  • Chaining exceptions: When handling an exception, you can preserve information about a previous exception (implicitly or using raise Exception from another_exception).

These features provide a flexible and powerful error handling mechanism in Python, allowing for the creation of more reliable and fault-tolerant programs.