Page 388 - CITS - Computer Software Application -TT
P. 388

COMPUTER SOFTWARE APPLICATION - CITS




           Output
           Exception in thread “main” java.lang.ArithmeticException: / by zero
           As displayed in the above example, the rest of the code is not executed (in such case, the rest of the code
           statement is not printed).
           There might be 100 lines of code after the exception. If the exception is not handled, all the code below the
           exception won’t be executed.

           Solution by exception handling
           Let’s see the solution of the above problem by a java try-catch block.
           Example 2
           TryCatchExample2.java
               public class TryCatchExample2 {


                   public static void main(String[] args) {
                       try
                       {
                       int data=50/0; //may throw exception

                       }
                           //handling the exception
                          catch(ArithmeticException e)
                       {
                           System.out.println(e);

                       }
                       System.out.println(“rest of the code”);
                   }


               }
           Output
           java.lang.ArithmeticException: / by zero
           rest of the code
           As displayed in the above example, the rest of the code is executed, i.e., the rest of the code statement is printed.
           Example 3

           In this example, we also kept the code in a try block that will not throw an exception.
           TryCatchExample3.java
               public class TryCatchExample3 {


                   public static void main(String[] args) {
                       try
                       {







                                                           375

 CITS : IT&ITES - Computer Software Application - Lesson 101 - 108  CITS : IT&ITES - Computer Software Application - Lesson 101 - 108
   383   384   385   386   387   388   389   390   391   392   393