Python Exception Handling

Exception handling in Python allows you to gracefully manage errors that might occur during program execution. This prevents your program from crashing.

Example 1: Basic `try-except` Block


    try:
      result = 10 / 0  # This will raise a ZeroDivisionError
    except ZeroDivisionError:
      print("Error: Cannot divide by zero")
        

The `try` block contains the code that might raise an exception. The `except` block catches the `ZeroDivisionError` and handles it appropriately.

Example 2: Handling Multiple Exceptions


    try:
      result = int("abc")  # This will raise a ValueError
    except ZeroDivisionError:
      print("Error: Division by zero")
    except ValueError:
      print("Error: Invalid input")
        

This shows how to handle different types of exceptions using multiple `except` blocks.

Example 3: `else` Block (for successful execution)


    try:
      result = 10 / 2
    except ZeroDivisionError:
      print("Error: Division by zero")
    else:
      print("Result:", result)  # Executed if no exception occurs
        

The `else` block is executed only if no exception occurs in the `try` block.

Example 4: `finally` Block (for cleanup)


    try:
      file = open("my_file.txt", "r")
    except FileNotFoundError:
      print("Error: File not found")
    finally:
      try:
        if 'file' in locals() and file:
          file.close()
      except NameError:
         print("No file to close")
        

The `finally` block is always executed, regardless of whether an exception occurred or not. It's useful for cleanup operations (closing files, releasing resources, etc.). The example now includes a `try...except` block within the `finally` to gracefully handle the case where a file object may not exist.

Example 5: Raising Custom Exceptions


    class InvalidAgeError(Exception):
      pass
    
    def check_age(age):
      if age < 0:
        raise InvalidAgeError("Age cannot be negative")
      elif age > 120:
        raise InvalidAgeError("Age seems too high")
      else:
        print("Valid age")
    
    
    try:
      check_age(-5)
    except InvalidAgeError as e:
      print(f"Error: {e}")
        

Important Considerations

  • Specific Exceptions: Catch exceptions by their specific type (`ZeroDivisionError`, `FileNotFoundError`, etc.) for more controlled error handling.
  • `else` Block: Use the `else` block to handle cases where the `try` block executes successfully.
  • `finally` Block: Employ the `finally` block for crucial cleanup tasks (e.g., closing files), even if exceptions occur.
  • Custom Exceptions: Create custom exception classes (like `InvalidAgeError`) to improve error handling for specific conditions.