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

COMPUTER SOFTWARE APPLICATION - CITS



           EXERCISE 107 : Use multiple try – catch blocks



            Objectives


           At the end of this exercise you shall be able to
           •  develop Java programs using  multiple try – catch blocks.

           Requirements

           Tools/Materials

           •  PC / laptop with windows OS
           •   SDK software
           •  Test editor (Visual studio/ subline/ notepad)

           Procedure

           // programs using  multiple try – catch blocks
           public class MultipleTryCatchExample {
               public static void main(String[] args) {
                   try {
                       // First try block
                       int[] numbers = {1, 2, 3};
                       System.out.println(“Element at index 5: “ + numbers[5]); // This will throw ArrayIndexOutOfBoundsException
                   } catch (ArrayIndexOutOfBoundsException e) {
                       System.out.println(“Caught ArrayIndexOutOfBoundsException: “ + e.getMessage());
                   }

                   try {
                       // Second try block
                       String str = null;
                       System.out.println(“Length of the string: “ + str.length()); // This will throw NullPointerException
                   } catch (NullPointerException e) {
                       System.out.println(“Caught NullPointerException: “ + e.getMessage());
                   }

                   try {
                       // Third try block
                       int result = 10 / 0; // This will throw ArithmeticException
                       System.out.println(“Result of division: “ + result);
                   } catch (ArithmeticException e) {
                       System.out.println(“Caught ArithmeticException: “ + e.getMessage());
                   }
               }
           }

           Output:
















                                                           157
 CITS : IT & ITES - Computer Software Application - Exercise 106
   167   168   169   170   171   172   173   174   175   176   177