Java OCA OCP Practice Question 831

Question

What two changes can you do, independent of each other, to make the following code compile:

//assume appropriate imports 
class MyClass  { 

    public MyClass (int port)  { 
        if  (Math .random () > 0.5)  { 
            throw new IOException (); 
         } /*from   www  .ja v  a 2  s  .co m*/

        throw new RuntimeException (); 
     } 
} 

public class Main  { 

    public static void main (String [] args)  { 
        try  { 
            MyClass pc = new MyClass (10); 
         } catch  (RuntimeException re)  { 
            re.printStackTrace (); 
         } 
     } 
} 

Select 2 options

  • A. add throws IOException to the main method.
  • B. add throws IOException to MyClass constructor.
  • C. add throws IOException to the main method as well as to MyClass constructor.
  • D. Change RuntimeException to java.io.IOException.
  • E. add throws Exception to MyClass constructor and change catch (RuntimeException re) to catch (Exception re) in the main method.


Correct Options are  : C E

Note

IOException is a checked exception and since the MyClass constructor throws IOException, this exception must be present in the throws clause of the constructor.

The main method has two options, either catch IOException in its catch block or put that exception in its throws clause.




PreviousNext

Related