Skip to content

Python try-finally without except

  • by

Python try-finally without except will not generates any error. If the finally clause executes a return, break, or continue statement, the saved exception is discarded.

try {

  // something

} finally {
  // guaranteed to run if execution enters the try block
}

Code after finally will be called whether the code after the try works or not. It doesn’t care. It is called every time.

If you need something to run IF AND ONLY IF the code in the try FAILS, then you need to use except.

Python try-finally without except

Simple example code.

from sys import argv

try:
x = argv[1] # Set x to the first argument if one is passed
finally:
x = 'default' # If no argument is passed (throwing an exception above) set x to 'default'
print('Finally')

print(x)

Output:

Python try-finally without except

Note: This is expected behavior. try:..finally:... alone doesn’t catch exceptions. Only the except clause of a try:...except:... does. So try:...finally:... is great for cleaning up resources.

Do comment if you have any doubts or suggestions on this Python exception-handling topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading