ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println(arr[5]);
} catch (Exception e) {
System.out.println("Exception caught");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("AIOOBE caught");
}
}
}- A. AIOOBE caught
- B. Exception caught
- C. Compilation error: AIOOBE catch is unreachable after catch(Exception)
- D. It crashes uncaught
Correct answer: C. Compilation error: AIOOBE catch is unreachable after catch(Exception)
ArrayIndexOutOfBoundsException is a subtype of Exception, so placing a broader catch(Exception e) before the narrower catch(ArrayIndexOutOfBoundsException e) makes the second one permanently unreachable — javac flags this as a compile-time error, same rule as ordering RuntimeException before a subtype.
More OOP with C++ and Java questions
- 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 {…
- What is printed? java enum Operation { ADD { public int apply(int a, int b) { return a + b; } }, MULTIPLY { public int apply(int a, int b)…
- What is printed? cpp class Shape { public: Shape& operator=(const Shape&) = delete; Shape() = default; }; int main() { Shape a, b; a = b; }
- What is printed? java class Parent { protected int score = 50; int getScore() { return score; } } class Child extends Parent { Child() {…