Java OCA OCP Practice Question 2812

Question

Which of the following changes when made independently would make this code compile?

(Choose all that apply.)

1:    public class Main implements AutoCloseable { 
2:       public void close() throws Exception { 
3:          throw new Exception("Exception!"); 
4:       } /*from w w  w  .jav  a  2  s . co  m*/
5:       public static void main(String[] args) { 
6:          try (Main t = new Main()) { 
7:            System.out.println("start"); 
8:          } 
9:       } 
10:   } 
  • A. Remove throws Exception from the declaration on line 2.
  • B. Add throws Exception to the declaration on line 5.
  • C. Change line 8 to } catch (Exception e) {}.
  • D. Change line 8 to } finally {}.
  • E. None of the above will make the code compile.
  • F. The code already compiles as is.


B, C.

Note

Option A is incorrect because it will move the compilation error to the close() method since it does throw an exception that must be handled or declared.

Option B is correct because the unhandled exception becomes declared.

Option C is correct because the exception becomes handled.

Option D is incorrect because the exception remains unhandled.




PreviousNext

Related