Python

Important Statements

Condition checking

The try Block

Contains the code that might raise an exception.

try:
    # Code that might cause an error
    risky_operation()
    another_risky_step()
    # ...

The except Block(s)

Catches and handles specific exceptions raised in the try block. You can have multiple except blocks for different exception types.

try:
    # Risky code
    result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
    # Code to handle ZeroDivisionError
    print("Error: Cannot divide by zero!")
except ValueError as e:
    # Code to handle ValueError, 'e' holds the exception object
    print(f"Value error occurred: {e}")
except Exception:
    # Catches any other exception (general handler)
    print("An unexpected error occurred.")

The else Block

Contains code that is executed only if the try block completes successfully without raising any exceptions.

try:
    # Risky code that might succeed
    file = open("my_file.txt", "r")
except FileNotFoundError:
    print("File not found.")
else:
    # Code to run if no exception occurred in try
    print("File opened successfully.")
    file.close()

The finally Block

Contains code that is always executed, regardless of whether an exception occurred in the try block or was handled by an except block. Often used for cleanup actions.