Python | Exceptions | finally statement

The finally statement is used to make sure the code runs no matter what error occurs. The finally statement is used in code after the try/except statement. Code within a finally statement always runs after execution of the code in the try, and possibly in the except, blocks.

Example:

try:
	print("Hello")
	print(5 / 0)
except ZeroDivisionError:
	print("Divided by zero")
finally:
	print("This code will run anyway!")

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
Hello
Divided by zero
This code will run anyway!
ddn_ro@linux:~/Desktop$ 

If an uncaught exception occurs the finally statement will run anyway.

try:
	print(1)
	print(5 / 0)
except ZeroDivisionError:
	print(unknown_var)
finally:
	print("This is executed last")

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
1
This is executed last
Traceback (most recent call last):
  File "file.py", line 5, in 
    print(unknown_var)
NameError: name 'unknown_var' is not defined
ddn_ro@linux:~/Desktop$

So, in case of a ZeroDivisionError the code should have printed the unknown_var but it can’t since it isn’t defined. The code goes ahead and executes the finally statement then the terminal shows the error NameError: name 'unknown_var' is not defined.

Leave a Reply