ProgrammingHardWipro · Cognizant pattern
Does this compile?
Does this compile?
class MyException extends Exception {}
class Demo {
void risky() throws MyException { throw new MyException(); }
void call() {
risky();
}
}- A. Yes, checked exceptions only need to be declared, not caught
- B. No: MyException is a checked exception, so call() must either catch it or declare throws MyException
- C. Yes, because MyException extends Exception rather than RuntimeException
- D. No: risky() cannot throw a custom exception type
Correct answer: B. No: MyException is a checked exception, so call() must either catch it or declare throws MyException
MyException extends Exception (not RuntimeException), making it a checked exception. Any method whose body can let a checked exception propagate must either catch it or declare it in its own throws clause; call() does neither, so it fails to compile.
More OOP with C++ and Java questions
- Does this compile? java class Demo { void risky() { throw new IllegalArgumentException(); } void call() { risky(); } }
- 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…