Java OCA OCP Practice Question 263

Question

Given:

class Main {//from  ww w.  j  av a 2 s . co  m
  public static void main(String[] args) {
    Main a = new Main();
    try {
      a.method1();
      a.method2();
      System.out.println("a");
    } // insert code here
      System.out.println("b");
    } catch (Exception e) {
      System.out.println("c");
    } }
  void method2() throws SQLException {
    throw new SQLException();
  }
  void method1() throws IOException {
    throw new IOException();
  }}

Which inserted independently at // insert code here will compile and produce the output: b?

Choose all that apply.

  • A. catch(Exception e) {
  • B. catch(FileNotFoundException e) {
  • C. catch(IOException e) {
  • D. catch(IOException | SQLException e) {
  • E. catch(IOException e | SQLException e) {
  • F. catch(SQLException e) {
  • G. catch(SQLException | IOException e) {
  • H. catch(SQLException e | IOException e) {


C, D, and G are correct.

Note

Since order doesn't matter, both D and G show correct use of the multi-catch block.

And C catches the IOException from method1() directly.

Note that method2() is never called at runtime.

However, if you remove the call, the compiler won't let you catch the SQLException since it would be impossible to be thrown.

A is incorrect because it will not compile.

Since there is already a catch block for Exception, adding another will make the compiler think there is unreachable code.

B is incorrect because it will print c rather than b.

Since FileNotFoundException is a subclass of IOException, the thrown IOException will not match the catch block for FileNotFoundException.

E and H are incorrect because they are invalid syntax for multi-catch.

The catch parameter e can only appear once.

F is incorrect because it will print c rather than b.

Since the IOException thrown by method1() is never caught, the thrown exception will match the catch block for Exception.




PreviousNext

Related