Page 134 - CA_Blue( J )_Class9
P. 134

6.9.1 try-catch
                  When an error occurs, whether due to a mistake in the code, incorrect input, or an issue with the hardware or
                  compiler, the program stops executing. In technical terms, we say that "Java has thrown an exception." The
                  keywords throw and throws are used to inform the compiler that an error has occurred. We can use try–catch
                  for the following purposes:
                  1.  “try” is the portion or block where code that may cause errors is written. If an error occurs, Java will throw an exception.
                  2.  “catch” is used to handle the exception that has been generated in the try block. In the catch block, we can write
                     our own error message or handle the error to suit our needs, rather than showing the system-generated message.
                  Syntax of try catch:
                      try
                      {  }
                      catch(Exception ex)
                             {     }

                                                                                        21 st
                   Some More Programs                                                 Century   #Coding & Computational Thinking
                                                                                        Skills

                   Program 1      Write a program to input two numbers and print the quotient.

                     1     import java.util.*;

                     2     class exception_handling
                     3     {

                     4         public static void main()
                     5         {

                     6             Scanner sc= new Scanner(System.in);
                     7             int a,b,q;

                     8             try
                     9             {
                    10                 System.out.print ("Enter 1st number ");

                    11                 a=sc.nextInt();

                    12                 System.out.print ("Enter 2nd number ");
                    13                 b=sc.nextInt();
                    14                 q=a/b;
                    15                 System.out.print (a+" divided by "+b+" is "+q);
                    16             }
                    17             catch(ArithmeticException e)

                    18             {
                    19                 System.out.println("Cannot divide by 0");
                    20             }
                    21         }

                    22     }



                   132    Touchpad Computer Applications-IX
   129   130   131   132   133   134   135   136   137   138   139