Page 91 - CA_Blue( J )_Class10
P. 91

5.7.2 Exception Handling
                 When an exception occurs, the program stops immediately with a system-generated message. To provide a user-
                 friendly message, we need to handle the raised exception. Using it, we can ensure that the flow of the program
                 doesn’t break when an exception occurs. To avoid such abnormal termination of programs, Java provides a concept
                 of exception handling. So, exception handling is a mechanism to handle errors occurred during the execution of the
                 program so that the normal flow of the program can be maintained. For handling exceptions in Java, the try-catch
                 statement is used.

                 5.7.3 The try-catch Statement
                 If an error occurs, say it might be an error in code, an error caused by wrong input or may be some error due to
                 hardware or compiler, the program stops executing. In technical terms, we say "Java has thrown an exception". We
                 can use try-catch for the following purposes:
                 •  "try" is a block where those statements are written which may produce some error and Java will throw an exception
                   for those errors.
                 •  "catch" block is used to handle the exception that has been generated in the try block. The catch block appears just
                   after the try block. In the catch block, we can write our own error message rather showing the system-generated
                   message.
                 Syntax of the try-catch statement is:

                        try {
                        // Block of code to try
                        } catch(Exception e) {
                        // Block  of code to handle errors
                        }
                 Where, Exception is the built-in Java class that is used to handle all types of exceptions.


                       Note: The catch block is the necessary block with the try block. Without catch block, try block will
                       not work.




                  Program 8    To input two integer numbers and print their sum.


                    1  import java.util.*;
                    2  class try_catch
                    3  {

                    4      public static void main()

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

                    8          try
                    9          {

                  10
                  11               System.out.println("Enter 2 numbers  : ");





                                                                                                                       89
                                                                                                         Input in Java   89
   86   87   88   89   90   91   92   93   94   95   96