Page 98 - computer science (868) class 11
P. 98

// 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               }


                9696  Touchpad Computer Science-XI
   93   94   95   96   97   98   99   100   101   102   103