Page 249 - IT-802_class_12
P. 249

Notes


                        Methods are the block of statements in a program which performs a specific task and can be reused
                        as and whenever required. They are also called Functions.



            In the above code, the calculate() method is called twice with different values. However, the code is written once in the
            method. This reduces the size of the program as well as the probability of committing mistakes is reduced.
              3.9 ExcEPtIon handLIng

            By now you may have written quite a few programs. Some of your programs when executed may have terminated
            unexpectedly with runtime errors. The errors could have occurred because an array index reference was out of range, or
            an attempt was made to divide an integer by zero, or there was insufficient computer memory and so on. Such an error
            situation that is unexpected in the program execution and causes it to terminate unexpectedly is called an exception. As
            a programmer, you should anticipate exceptions in your program that could lead to unpredictable results and handle the
            exceptions. Consider the program that has a method called divide().
            The method takes two numbers as parameters, divides them and returns the quotient:

            int divide (int dividend, int divisor)
            {
            return dividend/divisor;

            }
            public class Javaprograms {
            static int divide(int dividend, int divisor)
            {
                return dividend/divisor;
            }
                public static void main(String[] args) {
                    int quotient = divide(10,0);
                    System.out.println(“Quotient”);
                }
            }





























                                                                               Fundamentals of Java Programming  247
   244   245   246   247   248   249   250   251   252   253   254