Exception Handling
else and finally
Success blocks and guaranteed cleanup
Interview: Complete exception handling — tests understanding of the full try/except/else/finally flow
The else and finally blocks complete the exception handling picture. else runs only when no exception occurs (keeping try blocks small). finally runs always — whether an exception occurred or not — making it perfect for cleanup operations like closing files or connections.
Execution Flow
try: Code that might raise an exceptionexcept: Runs if matching exception is raisedelse: Runs only if NO exception was raised (after try succeeds)finally: Runs ALWAYS — success, failure, return, break, or continue
Why Use else?
The else block keeps your try block minimal. Only put code that might raise in try; put follow-up code in else. This prevents accidentally catching exceptions from code you didn't intend to protect.
Interview Tip
Know that finally runs even if the try/except block contains a return statement. The finally block executes before the return value is actually returned.
Use Cases
File handling: close files in finally regardless of success/failure
Database connections: always close connections and release resources
Lock management: acquire in try, release in finally
Timing operations: record duration in finally block
Logging: log success in else, log failure in except, log completion in finally
Common Mistakes
Putting success code in try instead of else (may catch unintended exceptions)
Forgetting that finally runs even after return/break/continue
Not handling the case where a resource was never created (NameError in finally)
Using finally for conditional cleanup (use context managers instead)
Returning a value in finally (overrides the try/except return value!)