Java OCA OCP Practice Question 1743

Question

Which can fill in the blank so this code outputs Caught it?

import java.util.*;
public class Main {
   public static void main(String[] args) {
      Optional opt = Optional.empty();
      try {//from w w  w.jav a  2  s.c o  m
         apply(opt);
      } catch (IllegalArgumentException e) {
         System.out.println("Caught it");
      }
   }
   private static void apply(Optional<Exception> opt) {
      opt.             (IllegalArgumentException::new);
   }
}
A. orElse
B. orElseGet
C. orElseThrow
D. None of the above. The main() method does not compile.


C.

Note

The main() method has warnings, but it does compile, making Option D incorrect.

The warnings are both about not declaring the generic type for Optional.

Option A does not compile because the orElse() method expects an Exception as the alternate value passed as a parameter.

IllegalArgumentException::new is a Supplier instead.

Options B and C both compile as both methods expect a Supplier as the parameter.

However, orElseGet() simply returns the exception from the method rather than throwing it.

Option C actually throws the exception the Supplier created and is the correct answer.




PreviousNext

Related