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

COMPUTER SOFTWARE APPLICATION - CITS




           EXERCISE 108 : Use the “throw” and “finally” keywords
                                        handle user defined exceptions



            Objectives

           At the end of this exercise you shall be able to
           •  develop Java programs using  “throw” and “finally” keywords handle user defined exceptions.


           Requirements
           Tools/Materials

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

           Procedure

           // Custom exception class

           class CustomException extends Exception {
               public CustomException(String message) {
                   super(message);
               }
           }

           public class ThrowFinallyExample {
               public static void main(String[] args) {
                   try {
                       // Simulating a condition where a custom exception is thrown
                       throwCustomException();

                   } catch (CustomException e) {
                       System.out.println(“Caught CustomException: “ + e.getMessage());
                   } finally {
                       // Code in the finally block will always be executed

                       System.out.println(“Finally block: This will execute whether an exception is thrown or not.”);
                   }
               }


               // Method that throws a custom exception
               private static void throwCustomException() throws CustomException {

                   // Using the ‘throw’ keyword to throw a custom exception
                   throw new CustomException(“This is a custom exception.”);
               }
           }




                                                           158
   168   169   170   171   172   173   174   175   176   177   178