Exception Handling in Python
else and finally
Use try, except, else and finally correctly.
A try statement can have two more optional parts: else and finally.
- The else block runs only if no exception occurred in the try block. It is a good place for code that should run only when everything went well, such as printing a result.
- The finally block always runs: whether an exception occurred or not, and whether it was handled or not. So it is used for clean-up work that must happen no matter what, such as closing a file.
The parts must come in this order:
try → except (one or more) → else → finally
What if an exception happens but no except block matches it? Python first runs the finally block, and then raises the exception again, so the program still stops with that error. For example, if int('var') raises a ValueError and there is no ValueError handler, the finally block prints its message (such as 'OVER AND OUT'), and then the ValueError appears.
So, in short: else runs when all is well; finally runs always.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.