Java OCA OCP Practice Question 2428

Question

Consider the following code and then select the correct options. (Choose all that apply.)

public class Main {
    public void readFile(String file) throws IOException {        // line1
        System.out.println("readFile");                           // line2
    }/* www .j a v  a 2  s.  co m*/
    void useReadFile(String name) throws IOException{             // line3
        try {
            readFile(name);
        }
        catch (IOException e) {
            System.out.println("catch-IOException");
        }
    }
    public static void main(String args[]) throws Throwable{      // line4
        new Main().useReadFile("foo");                  // line5
    }
}
a  Code on both line 1 and line 2 causes compilation failure.
b  Code on either line 1 or line 2 causes compilation failure.
c  If code on line 1 is changed to the following, the code will compile successfully:

public void readFile(String file) {d)

d  A change in code on line 3 can prevent compilation failure:

void useReadFile(String name) {

e  Code on either line 4 or line 5 causes compilation failure. If line 4 is changed to the following, a Main will compile:

public static void main(String args[]) throws Exception {


f

Note

The code as is (without any changes) compiles successfully.

Options (a) and (b) are incorrect because a method (readFile()) can declare a checked exception (IOException) to be thrown in its throws clause, even if the method doesn't throw it.

Option (c) is incorrect.

If line 1 is changed so that method readFile() doesn't declare to throw an IOException, method useReadFile() won't compile.

The catch block in method useReadFile() tries to handle IOException, which isn't thrown by its try block.

This causes compilation error.

Option (d) is incorrect.

Code on line 3 will compile as it is.

It's okay for useReadFile() to handle the exception thrown by readFile() using try-catch and still declare it to be rethrown using the throws clause.

Option (e) is incorrect.

The code compiles successfully.

Option (f) is correct.

Even though useReadFile() handles IOException and doesn't actually throw it, it declares it to be rethrown in its throws clause.

So, the method that uses useReadFile() must either handle the checked exception-IOException (or one of its super classes)-or declare it to be rethrown.

Because Exception is a superclass of IOException, replacing throws Throwable with throws Exception in the declaration of method main() enables the code to compile.




PreviousNext

Related