Java OCA OCP Practice Question 361

Question

A new 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 void processArray(int[] values) {
      int sum = 0;
      int i = 0;//from  w ww . j  av  a  2s. co m
      try {
         while (values[i] < 100) {
            sum = sum + values[i];
            i++;
         }
      } catch (Exception e) {
      }
      System.out.println("sum = " + sum);
   }
}

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 because at run time.

If the exception is thrown, the program will not show any sign of the exception and may produce bad results that will be hard to debug.

It is a good practice to at least print out the exception if you don't want to do any thing upon encountering an exception.




PreviousNext

Related