Java OCA OCP Practice Question 261

Question

Given:

class Main {/*from ww w  . j a v a 2s  .c o m*/
   public static void main(String[] args) {
            Main a = new Main();
            try {
              a.myMethod();
              System.out.println("a");
            } catch (IOException e | SQLException e) {
              System.out.println("c");
            } finally {
              System.out.println("d");
            }
          }

   void myMethod() throws IOException, SQLException {
      throw new SQLException();
   }
}

What is the result?

  • A. ad
  • B. acd
  • C. cd
  • D. d
  • E. Compilation fails
  • F. An exception is thrown at runtime


E is correct.

Note

catch (IOException e | SQLException e) doesn't compile.

While multiple exception types can be specified in the multi-catch, only one variable name is allowed.

The correct syntax is catch (IOException | SQLException e).

It is legal for myMethod() to have IOException in its signature even though that Exception can't be thrown.

If the catch block's syntax error were corrected, the code would output cd.

The multi-catch would catch the SQLException from myMethod() since it is one of the exception types listed.

The finally block runs at the end of the try/catch.




PreviousNext

Related