Page 288 - CTS - CSA TP - Volume 2
P. 288

COMPUTER SOFTWARE APPLICATION - CITS




           EXERCISE 131 : Use exception handling in python program


            Objectives


           At the end of this exercise you shall be able to
           •  develop python program  for exception handling.

           Procedure


           Exception  handling  in  Python  is  done  using  the  try,  except,  else,  and  finally  blocks.  Here  are  five  examples
           demonstrating different use cases for exception handling
           TASK 1: Division by Zero

           # Example 1: Division by Zero
           try:
           numerator=int(input(“Enter the numerator: “))
           denominator=int(input(“Enter the denominator: “))
           result=numerator/denominator

           exceptZeroDivisionError:
           print(“Error: Division by zero is not allowed.”)
           else:
           print(f”Result: {result}”)

           finally:
           print(“This block always executes, regardless of exceptions.”)
           Explanation:
           •  We use try to enclose the code that might raise an exception.
           •  except Zero Division Error catches the specific exception if the denominator is zero.

           •  else block executes if there are no exceptions.
           •  finally block always executes, regardless of whether there is an exception or not.
           Output:






























                                                           273
 CITS : IT & ITES - Computer Software Application - Exercise 130
   283   284   285   286   287   288   289   290   291   292   293