1.

When should finally clause be used in exception handling process?

Answer»

Python’s exception handling technique INVOLVES four keywords: try, except, else and finally. The try block is essentially a script you want to check if it contains any runtime ERROR or exception. If it does, the exception is raised and except block is executed. 

The else block is optional and will get run only if there is no exception in try block. Similarly, finally is an optional clause meant to perform clean up operations to be undertaken under all circumstances, whether try block encounters an exception or not. A finally clause is ALWAYS executed before leaving the try statement, whether an exception has occurred or not. 

>>> try: raise TypeError finally: print ("end of exception handling") end of exception handling Traceback (most recent call last):   File "<pyshell#28>", line 2, in <MODULE>     raise TypeError TypeError

When an unhandled exception occurs in the try block (or it has occurred in an except or else clause), it is re-raised after the finally block executes. The finally clause is also executed when either try, except or else block is left via a break, continue or return statement.

>>> def division(): try: a=int(input("first number")) b=int(input("second number")) c=a/b except ZeroDivisionError: print ('divide by 0 not allowed') else: print ('division:',c) finally: print ('end of exception handling')

Let US call above function number of times to see how finally block works:

>>> division() first number10 second number2 division: 5.0 end of exception handling >>> division() first number10 second number0 divide by 0 not allowed end of exception handling >>> division() first number10 second numbertwo end of exception handling Traceback (most recent call last):   File "<pyshell#47>", line 1, in <module>     division()   File "<pyshell#42>", line 4, in division     b=int(input("second number")) ValueError: invalid literal for int() with base 10: 'two'

Note how exception is re-raised after the finally clause is executed. The finally block is typically used for releasing external resources such as file whether or not it was successfully used in previous clauses.



Discussion

No Comment Found