ProgrammingHardWipro · Cognizant pattern
Does this compile?
Does this compile?
public class Main {
public static void main(String[] args) {
try {
throw new RuntimeException("x");
} catch (RuntimeException e) {
System.out.println("generic");
} catch (IllegalArgumentException e) {
System.out.println("specific");
}
}
}- A. Yes, and it prints generic
- B. No: IllegalArgumentException is unreachable because RuntimeException, a broader supertype, is caught first
- C. Yes, and it prints specific
- D. No: catch blocks must be ordered alphabetically
Correct answer: B. No: IllegalArgumentException is unreachable because RuntimeException, a broader supertype, is caught first
IllegalArgumentException IS-A RuntimeException, so once the earlier, broader catch(RuntimeException) is present, the later, narrower catch(IllegalArgumentException) can never be reached for ANY exception — javac detects this and rejects it as unreachable code at compile time.
More OOP with C++ and Java questions
- What is printed? java public class Main { public static void main(String[] args) { try { Object[] arr = new String[3]; arr[0] = 100; }…
- What is printed? cpp void f() { try { throw 10; } catch (double d) { cout << "double:" << d; } catch (int i) { cout << "int:" << i; } }…
- What is printed? java public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3}; try {…
- What is printed? java class Base { final void secure() { System.out.print("Base.secure"); } } class Derived extends Base { // void…
- What is printed? cpp class Base { public: virtual void f() final { cout << "Base::f "; } }; class Derived : public Base { public: // void…
- What is printed? cpp struct Base { Base() { cout << "Base() "; } }; struct Mixin1 { Mixin1() { cout << "Mixin1() "; } }; struct Mixin2 {…