Page 122 - Cs_withBlue_J_C11_Flipbook
P. 122

// Method defined here
                  }
              Java finally block
              A finally keyword follows after the try block. This block, if present, always executes whether there is an exception or
              not. It appears at the end of the catch block.
              Syntax of finally block:
                  finally
                  {
                  //Statement that has to be executed even if there is no error
                  }

                Program 2     Program to divide two numbers without exception handling.


                1       class withoutexceptionhandling
                2       {

                3           public static void main()
                4           {

                5               int a=44, b=0,result;
                6               result=a/b;

                7               b=2;
                8               result=a/b;

                9               System.out.println("Answer : "+result);
                10          }

                11      }
              The program will return the following error when executed:

                  /*
                   * java.lang.ArithmeticException: / by zero
                      at withouthandlingexception.main(withouthandlingexception.java:6)
                  */

                Program 3     Program to divide two numbers with exception handling.


                1       class exceptionhandling
                2       {

                3           public static void main()
                4           {

                5               int a=44,b=0,result;
                6               try

                7              {
                8                   result=a/b;

                9               }


                120120  Touchpad Computer Science-XI
   117   118   119   120   121   122   123   124   125   126   127