Java OCA OCP Practice Question 3129

Question

What will be printed when the program is compiled and run?

class MyClass<E extends Exception> {
  public void throwOne(E e) throws E {
    throw e;// w ww .j a v a  2  s.  c  om
  }
}

class Exception1 extends Exception {
  Exception1(String str) {
    super(str);
  }
}

public class Main {
  public static void main(String[] args) {
    MyClass<Exception1> tantrum = new MyClass<Exception1>();
    try {
      tantrum.throwOne(new Exception1("MyClass thrown."));
    } catch (Exception1 te) {
      System.out.println(te.getMessage());
    }
  }
}

Select the one correct answer.

  • (a) The class MyClass will not compile.
  • (b) The class Main will not compile.
  • (c) The program will compile, print "MyClass thrown.", and terminate normally when run.
  • (d) The program will compile and will throw an exception and abort the execution when run.


(c)

Note

The type parameter E in the class MyClass has the upper bound Exception, and the method throwOne() can throw an exception that is a subtype of Exception.

The generic MyClass class is instantiated correctly in the main() method, as is the non-generic class Exception1 that is a subtype of Exception.




PreviousNext

Related