Finally keyword in Python


In any programming language we find a situation where exceptions are raised. Python has many inbuilt exception handling mechanisms. There are errors which are handled by this exception names. Python also has a block called finally which is executed irrespective of whether the exception is handled or not.

Syntax

try:
   # main python Code....
except:
   # It is optional block
   # Code to handle exception
finally:
   # This Code that is always executed

Example

In the below code we see an exception called NameError. Here we create a code which refers to undeclared variables. Even though the exception is handled the code still runs into the "finally" Block. The code in the "finally" block gets executed as well.

try:
   var1 = 'Tutorials'
   # NameError is raised
   print(var2)

# Handle the exception
except NameError:
   print("variable is not found in local or global scope.")
finally:
   # Regardless of exception generation,
   # this block is always executed
   print('finally block code here')

Output

Running the above code gives us the following result −

variable is not found in local or global scope.
finally block code here

Without Exception Handling

Suppose we design the code not to handle the exception. Even then the finally block will execute the code for the unhandled exceptions.

Examples

try:
   var1 = 'Tutorials'
   # NameError is raised
   print(var2)
# No exception handling
finally:
   # Regardless of exception generation,
   # this block is always executed
   print('finally block code here')

Output

Running the above code gives us the following result −

finally block code here
Traceback (most recent call last):
   File "xxx.py", line 4, in
      print(var2)
NameError: name 'var2' is not defined

Updated on: 07-Aug-2019

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements