Java OCA OCP Practice Question 1173

Question

A Java programmer has written the following method that takes an array of integers and sums up all the integers that are less than 100.

public class Main {
   public static void processArray(int[] values) {
      int sum = 0;
      int i = 0;//from  w ww  . j a  va2  s . com
      try {
         while (values[i] < 100) {
            sum = sum + values[i];
            i++;
         }
      } catch (Exception e) {
      }
      System.out.println("sum = " + sum);
   }

   public static void main(String args[]) {
      int[] a = { 1, 2, 3, 4, 5 };
      processArray(a);

   }
}

Which of the following are best practices to improve this code?

Select 2 options

  • A. Use ArrayIndexOutOfBoundsException for the catch argument.
  • B. Use ArrayIndexOutOfBoundsException for the catch argument and add code in the catch block to log or print the exception.
  • C. Add code in the catch block to handle the exception.
  • D. Use flow control to terminate the loop.


Correct Options are  : B D

Note

Empty catch blocks are a bad practice.

At run time, if the exception is thrown, the program will not show any sign of the exception.




PreviousNext

Related