Error Handling

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:

Python

When the try succeeds, both else and finally run:

Python
Output

When the try fails, except and finally run, else is skipped:

Python
Output

What will be the output?

Python

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.

Python
Output

What will be the output?

Python

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:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python