Phase 3 of 25 · Topic 3.5

Try-Except-Else-Finally Execution Semantics

1Concept

1. `try`: Wraps hazardous operations; 2. `except`: Handles matching exceptions; 3. `else`: Executes ONLY when no exception occurred in the try block (separating success logic from hazardous code); 4. `finally`: ALWAYS executes, guaranteed cleanup.

2Architecture Diagram

try Block ---> No Exceptions ---> [ else Block Executes ] ---> [ finally Block ALWAYS Runs ]
          ---> Exception Caught ---> [ except Block Runs ] ---> [ finally Block ALWAYS Runs ]

3Code Example

Python 3.12
def process_database_query(valid_connection: bool):
    try:
        print("1. Initiating connection...")
        if not valid_connection:
            raise ConnectionError("PostgreSQL port unreachable")
    except ConnectionError as err:
        print(f"2. Handled failure: {err}")
    else:
        print("2. Success: Database query executed with zero errors!")
    finally:
        print("3. Finally: Releasing connection back to pool.")

print("=== Successful Execution Flow ===")
process_database_query(True)
print("\n=== Failure Execution Flow ===")
process_database_query(False)

4Expected Output

=== Successful Execution Flow ===
1. Initiating connection...
2. Success: Database query executed with zero errors!
3. Finally: Releasing connection back to pool.

=== Failure Execution Flow ===
1. Initiating connection...
2. Handled failure: PostgreSQL port unreachable
3. Finally: Releasing connection back to pool.

5Key Takeaways

  • Use the `else` block to keep the `try` block minimal, avoiding catching unintended exceptions.
  • Code in `finally` executes even if `return`, `break`, or `continue` is invoked.
  • Returning from `finally` silently suppresses exceptions thrown in `try`.