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();
    }
}
  1. A. It fails to compile because main does not declare throws IllegalArgumentException
  2. B. It compiles fine; unchecked exceptions never require a throws clause or try/catch
  3. C. It compiles fine only because Math.random() < 2 is always true
  4. 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

Exams that ask this topic