else, finally, and Raising
Scenario: A lock must release whether deployment succeeds or fails.
New words, in plain English
- else clause - runs when try completed without exception
- finally clause - runs whether an exception happened or not
- raise - create or re-throw an exception
Use else for success-only work and finally for unavoidable cleanup. raise rejects invalid state; bare raise re-throws the current exception.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
handle = open("deploy.log", "a")
try:
handle.write("start\n")
else:
print("logged")
finally:
handle.close()
Tip: A with statement is usually cleaner than manual open/finally for files.
Goal: Practice this idea in the py-exception-handling challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.