Saturday 5 December 2015

Python: finally clause


‘finally’ clause is used to perform clean up operations, ‘finally’ block always executes before leaving try statement (whether exception occurred or not, doesn’t matter). A typical try block looks like below.
try:
 statements
except ZeroDivisionError:
 statements
else:
 statements
finally:
 statements


test.py
def div(a, b):
 try:
  result = a/b
 except ZeroDivisionError:
  print("b should not be zero")
 else:
  print("Result : ", result)
 finally:
  print("executing finally clause")

>>> import test
>>> test.div(10, 2)
Result :  5.0
executing finally clause
>>> 
>>> test.div(5, 0)
b should not be zero
executing finally clause


In real world applications, finally clause is used to close the resources like files, network socket connections etc.,




Previous                                                 Next                                                 Home

No comments:

Post a Comment