Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The try/except/finally Block in Python

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

** Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement! **

Tips and Traps

  1. The finally statements are guaranteed to be executed (presuming no power outage or anything outside of Python’s control) after a try/except block runs even if return, break or continue is used in a try/except block. This mean that a if a finally block presents the function won’t exit immediate on reaching a return statement in a try/except block. Instead, the function will wait until the finally block is executed to exit. If another return statement is run in the finally block, the previous return value is overwritten. This means that you should never use a return/yield statement in a finally block.

Beginning of the try block (before return) ...
Beginning of the finally block (before return) ...
-1
Beginning of the exception block (before return) ...
Beginning of the finally block (before return) ...
-1
Beginning of the exception block (before return) ...
The finally block is run.
1