Open In App

finally keyword in Python

Last Updated : 02 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisites: Exception Handling, try and except in Python In programming, there may be some situation in which the current method ends up while handling some exceptions. But the method may require some additional steps before its termination, like closing a file or a network and so on. So, in order to handle these situations, Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception. Syntax:

try:
       # Some Code.... 

except:
       # optional block
       # Handling of exception (if required)

finally:
      # Some code .....(always executed)      

Important Points –

  • finally block is always executed after leaving the try statement. In case if some exception was not handled by except block, it is re-raised after execution of finally block.
  • finally block is used to deallocate the system resources.
  • One can use finally just after try without using except block, but no exception is handled in that case.

Example #1: 

Python3




# Python program to demonstrate finally
 
# No exception Exception raised in try block
try:
    k = 5//0 # raises divide by zero exception.
    print(k)
 
# handles zerodivision exception   
except ZeroDivisionError:  
    print("Can't divide by zero")
     
finally:
    # this block is always executed
    # regardless of exception generation.
    print('This is always executed')


Output:

Can't divide by zero
This is always executed

  Example #2: 

Python3




# Python program to demonstrate finally
 
try:
    k = 5//1 # No exception raised
    print(k)
 
# intends to handle zerodivision exception   
except ZeroDivisionError:  
    print("Can't divide by zero")
     
finally:
    # this block is always executed
    # regardless of exception generation.
    print('This is always executed')


Output:

5
This is always executed

  Example #3: 

Python3




# Python program to demonstrate finally
 
# Exception is not handled
try:
    k = 5//0 # exception raised
    print(k)
     
finally:
    # this block is always executed
    # regardless of exception generation.
    print('This is always executed')


Output: 

This is always executed

Runtime Error –

Unhandled Exception 
    k=5//0 #No exception raised
ZeroDivisionError: integer division or modulo by zero

Explanation: In above code, the exception is generated integer division or modulo by zero, which was not handled. The exception was re-raised after execution of finally block. This shows that finally block is executed regardless of exception is handled or not.

Example #4:

Python3




# Example 4
def learnfinally():
    try:
        print("Inside try Block"# No Exception raised
        return 1                   # before this, finally gets executed
    except Exception as e:
        print(e)
    finally:
        print("Inside Finally")
 
 
print(learnfinally())


Output:

Inside try Block
Inside Finally
1

Explanation: In above code, as the control reaches to return statement in try block, it transfers the control to finally block and finally block gets executed. This shows that finally block gets executed even after hitting the return statement in try block.



Similar Reads

Try, Except, else and Finally in Python
An Exception is an Unexpected Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which prevents your program from interrupting. Example: In this code, The system can not divide the number with zero so an ex
4 min read
Python | Passing dictionary as keyword arguments
Many times while working with Python dictionaries, due to advent of OOP Paradigm, Modularity is focussed in different facets of programming. Hence there can be many use cases in which we require to pass a dictionary as argument to a function. But this required the unpacking of dictionary keys as arguments and it's values as argument values. Let's d
3 min read
Python | yield Keyword
In this article, we will cover the yield keyword in Python. Before starting, let's understand the yield keyword definition. Syntax of the Yield Keyword in Python def gen_func(x): for i in range(x): yield iWhat does the Yield Keyword do? yield keyword is used to create a generator function. A type of function that is memory efficient and can be used
4 min read
Python assert keyword
Python Assertions in any programming language are the debugging tools that help in the smooth flow of code. Assertions are mainly assumptions that a programmer knows or always wants to be true and hence puts them in code so that failure of these doesn't allow the code to execute further. Assert Keyword in PythonIn simpler terms, we can say that ass
7 min read
Global keyword in Python
In this article, we will cover the global keyword, the basic rules for global keywords in Python, the difference between the local, and global variables, and examples of global keywords in Python. What is the purpose of global keywords in python? A global keyword is a keyword that allows a user to modify a variable outside the current scope. It is
5 min read
Python program to check if a given string is Keyword or not
Given a string, write a Python program that checks if the given string is keyword or not. Keywords are reserved words which cannot be used as variable names.There are 33 keywords in Python programming language.(in python 3.6.2 version) Examples: Input: str = "geeks" Output: geeks is not a keyword Input: str = "for" Output: for is a keyword We can a
3 min read
Keyword Module in Python
Python provides an in-built module keyword that allows you to know about the reserved keywords of python. The keyword module allows you the functionality to know about the reserved words or keywords of Python and to check whether the value of a variable is a reserved word or not. In case you are unaware of all the keywords of Python you can use thi
2 min read
Use of nonlocal vs use of global keyword in Python
Prerequisites: Global and Local Variables in PythonBefore moving to nonlocal and global in Python. Let us consider some basic scenarios in nested functions. C/C++ Code def fun(): var1 = 10 def gun(): print(var1) var2 = var1 + 1 print(var2) gun() fun() Output: 10 11 The variable var1 has scope across entire fun(). It will be accessible from nested f
3 min read
is keyword in Python
In programming, a keyword is a “reserved word” by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. Python language also reserves some of the keywords that convey special meaning. In Python, keywords are case-sensitive. Python is Keywo
2 min read
Python IMDbPY - Searching keyword
In this article we will see how we can search a keyword in the IMDb database.Keyword : It is a word (or group of connected words) attached to a title (movie / TV series / TV episode) to describe any notable object, concept, style or action that takes place during a title. The main purpose of keywords is to allow visitors to easily search and discov
1 min read
Article Tags :
Practice Tags :