Java OCA OCP Practice Question 1796

Question

Which digits, and in what order, will be printed when the following program is run?.

public class Main {
  public static void main(String[] args) {
    int k=0;/* w  w  w  . j a  v  a2s.  co m*/
    try {
      int i = 5/k;
    } catch (ArithmeticException e) {
      System.out.println("1");
    } catch (RuntimeException e) {
      System.out.println("2");
      return;
    } catch (Exception e) {
      System.out.println("3");
    } finally {
      System.out.println("4");
    }
    System.out.println("5");
  }
}

Select the one correct answer.

  • (a) The program will only print 5.
  • (b) The program will only print 1 and 4, in that order.
  • (c) The program will only print 1, 2, and 4, in that order.
  • (d) The program will only print 1, 4, and 5, in that order.
  • (e) The program will only print 1, 2, 4, and 5, in that order.
  • (f) The program will only print 3 and 5, in that order.


(d)

Note

The program will only print 1, 4, and 5, in that order.

The expression 5/k will throw an ArithmeticException, since k equals 0.

Control is transferred to the first catch block, since it is the first block that can handle arithmetic exceptions.

This exception handler simply prints 1.

The exception has now been caught and normal execution can resume.

Before leaving the try statement, the finally block is executed.

This block prints 4.

The last statement of the main() method prints 5.




PreviousNext

Related