finally keyword in Python
Last Updated :
02 Mar, 2023
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
try :
k = 5 / / 0
print (k)
except ZeroDivisionError:
print ("Can't divide by zero")
finally :
print ( 'This is always executed' )
|
Output:
Can't divide by zero
This is always executed
Example #2:
Python3
try :
k = 5 / / 1
print (k)
except ZeroDivisionError:
print ("Can't divide by zero")
finally :
print ( 'This is always executed' )
|
Output:
5
This is always executed
Example #3:
Python3
try :
k = 5 / / 0
print (k)
finally :
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
def learnfinally():
try :
print ( "Inside try Block" )
return 1
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.
Please Login to comment...