ProgrammingHardWipro · Cognizant pattern
Which statement about this code is correct?
Which statement about this code is correct?
class Main {
static void risky() {
if (Math.random() < 2) throw new IllegalArgumentException("bad");
}
public static void main(String[] args) {
risky();
}
}- A. It fails to compile because main does not declare throws IllegalArgumentException
- B. It compiles fine; unchecked exceptions never require a throws clause or try/catch
- C. It compiles fine only because Math.random() < 2 is always true
- D. It fails to compile because risky() has no return type matching an exception
Correct answer: B. It compiles fine; unchecked exceptions never require a throws clause or try/catch
IllegalArgumentException is an unchecked exception (it extends RuntimeException), and Java never forces a method to declare or catch unchecked exceptions, so this compiles regardless of the method body's logic; at run time it will indeed always throw since Math.random() returns a value in [0,1) which is always < 2.
More OOP with C++ and Java questions
- What is printed? java public class Main { public static void main(String[] args) { int result = compute(); System.out.println(result); }…
- What is printed? java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); try {…
- What is printed? cpp struct Logger { Logger() { cout << "open "; } ~Logger() noexcept(false) { cout << "close "; throw…
- What is printed? java public class Main { public static void main(String[] args) { try { level1(); } catch (RuntimeException e) {…
- What is printed? java class MyException extends RuntimeException { MyException(String m) { super(m); } } public class Main { public static…
- What is printed? java public class Main { public static void main(String[] args) { int i = 0; while (true) { try { i++; if (i == 3) break…