Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 28
Given code of Test.java file:
- package com.udayan.ocp;
- import java.util.OptionalDouble;
- class MyException extends RuntimeException{}
- public class Test {
- public static void main(String[] args) {
- OptionalDouble optional = OptionalDouble.empty();
- System.out.println(optional.orElseThrow(MyException::new));
- }
- }
What will be the result of compiling and executing Test class?
- A An instance of NoSuchElementException is thrown at runtime
- B An instance of MyException is thrown at runtime
- C An instance of NullPointerException is thrown at runtime
- D An instance of RuntimeException is thrown at runtime
- E Compilation error
- F null
Reveal correct answer
Correct answer: B
Explanation
orElseThrow throws the instance of provided Exception if optional is empty.
In this case optional is an empty OptionalDouble, hence an instance of MyException is thrown at runtime.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
You must be logged in to post a comment.
