else and finally
A try block can have two more parts: else runs only when no exception was raised, and finally runs no matter what. Both are useful for cleanup and post-success steps.
A try block can have two more parts. The else clause runs only when nothing went wrong, and finally runs no matter what.
Full syntax with all four blocks:
When the try succeeds, both else and finally run:
When the try fails, except and finally run, else is skipped:
What will be the output?
Why bother with else? It separates the code that might fail from the code that runs after success. Anything in else is guaranteed not to be caught by the except above.
With else, code that should only run on success is safely outside the try, so its errors will not be swallowed by the except above.
What will be the output?
The finally block is for cleanup. It runs whether the try succeeded, an exception was caught, or even an unhandled exception bubbled out.
A counter that always increments:
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?