Exception in a program as a situation that occurs during runtime and programmer has no control on it.
A good program is one that has a code that handles an exception well i.e., in case an exception occurs, then the exception handling code written for it, will take over and do the necessary action.
Exception handling in python involves the use of try-except-finally clauses wherein the code that may generate an exception is written in the try block and the code for handling the exception when the exception is raised, written in except block. Code written under finally clause will be executed no matter if the try block raises an error or not.
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.
try: #some code except: #Handling exception finally: #always executed code.
try: print("result of 10/5=", (10/5)) print("result of 10/0=", (10/0)) except: print("Denominator must not be zero.") finally: print("This block is always executed.")
Output- result of 10/5= 2.0 Denominator must not be zero. This block is always executed.
This is all about try-except-finally clause in python.