Java OCA OCP Practice Question 1501

Question

Consider the following code:

class Main  { //from   w ww  .  j a va 2s.co m
    public void doMain (int k) throws Exception  {  // 0 
        for (int i=0; i< 10; i++)  { 
            if (i == k) throw new Exception ("Index of k is "+i); // 1 
         } 
     } 
    public void doB (boolean f)  { // 2 
        if (f)  { 
            doMain (15); // 3 
         } 
        else return; 
     } 
    public static void main (String [] args)  { // 4 
        Main a = new Main (); 
        a.doB (args.length>0); // 5 
     } 
  } 

Which of the following statements are correct?

Select 1 option

  • A. This will compile and run without any errors or exception.
  • B. This will compile if throws Exception is added at line //2
  • C. This will compile if throws Exception is added at line //4
  • D. This will compile if throws Exception is added at line //2 as well as //4
  • E. This will compile if line marked // 1 is enclosed in a try catch block.


Correct Option is  : D

Note

Any checked exceptions must be either handled using a try block or the method that generates the exception must declare that it throws that exception.

In this case, doMain() declares that it throws Exception.

doB () is calling doMain but it is not handling the exception generated by doMain ().

So, it must declare that it throws Exception.

Now, the main () method is calling doB (), which generates an exception.

Therefore, main () must also either wrap the call to doB () in a try block or declare it in its throws clause.

The main (String [] args) method is the last point in your program where any unhandled checked exception can bubble up to.

After that the exception is thrown to the JVM and the JVM kills the thread.




PreviousNext

Related