Finally Clause

'''
Finally Clause:
It is also a part of exception handling.
When we use exception using try and except block, we can include a finally block at the end.
The finally block is always executed, so it is generally used for doing the concluding tasks like closing file resources or closing database connection or maybe ending the program execution with a delightful message.

Syntax:
try:
    statements which could generate exceptions
except:
    solution of generated exception
finally:
    Block of code which is going to execute at any situation 

The finally block is executed irrespective of the outcome of the try...except...else block.
'''

try:
    l = (1, 5, 7, 13)
    i = int(input("Enter the index: "))
    print(l[i])
except:
    print("Some error occurred")

finally:
    print("I am always executed")
# output = 
# Enter the index: 0
# 1
# I am always executed

# output = 
# Enter the index: 4
# Some error occurred
# I am always executed

# output = 
# Enter the index: sindhu
# Some error occurred
# I am always executed

try:
    l = (1, 5, 7, 13)
    i = int(input("Enter the index: "))
    print(l[i])
except:
    print("Some error occurred")

print("I am always executed")
# output = 
# Enter the index: 4
# Some error occurred
# I am always executed
# Here "I am always executed runs irrespective whether we use finally block or not."

def func1():
    try:
        l = (1, 5, 7, 13)
        i = int(input("Enter the index: "))
        print(l[i])
        return 1
    except:
        print("Some error occurred")
        return 0

print("I am always executed")

x = func1()
print(x)
# output = 
# Enter the index: 0
# 1
# 1
# I am always executed didn't run.

def func1():
    try:
        l = (1, 5, 7, 13)
        i = int(input("Enter the index: "))
        print(l[i])
        return 1
    except:
        print("Some error occurred")
        return 0
    finally:
        print("I am always executed")

x = func1()
print(x)
# output = 
# Enter the index: 0
# 1
# I am always executed
# 1
# Here, I am always executed runs.

# output = 
# Enter the index: 4
# Some error occurred
# I am always executed


Comments

Popular posts from this blog

Print Function

Arithmetic Operators

Sets in Python