ProgrammingHardHCL · Tech Mahindra pattern
Does this compile?
Does this compile?
class Demo {
void risky() { throw new IllegalArgumentException(); }
void call() {
risky();
}
}- A. No: risky() must declare throws IllegalArgumentException
- B. Yes: IllegalArgumentException is unchecked (a RuntimeException), so it need not be declared or caught
- C. Yes, but only because call() is void
- D. No: unchecked exceptions must still be caught somewhere
Correct answer: B. Yes: IllegalArgumentException is unchecked (a RuntimeException), so it need not be declared or caught
IllegalArgumentException extends RuntimeException, making it unchecked. Unchecked exceptions are exempt from Java's compile-time catch-or-declare requirement, so this compiles even though neither method mentions it.
More OOP with C++ and Java questions
- What is printed? java public class Main { public static void main(String[] a) { int[] arr = {1, 2, 3}; try { System.out.print(arr[5]); }…
- What is printed? java public class Main { static void a() { b(); } static void b() { c(); } static void c() { throw new…
- Does this compile? java public class Main { public static void main(String[] a) { try { throw new RuntimeException(); } catch (Exception…
- What is printed? java class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) {…
- What is printed? java public class Main { public static void main(String[] args) { String a = "hello"; String b = "hello"; String c = new…
- What is printed? java public class Main { public static void main(String[] args) { String a = "hello"; String c = new…