ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class MyChecked extends Exception {}
class Test {
static void risky() throws MyChecked { throw new MyChecked(); }
public static void main(String[] args) {
try {
risky();
} catch (Exception e) {
System.out.println("caught: " + e.getClass().getSimpleName());
}
}
}- A. Compilation error: MyChecked must be caught specifically, not as Exception
- B. caught: Exception
- C. Uncaught exception at runtime
- D. caught: MyChecked
Correct answer: D. caught: MyChecked
A catch(Exception e) clause catches any exception of type Exception or any subclass, including the custom checked MyChecked. getClass().getSimpleName() reports the actual runtime class, MyChecked, not the static catch type.
More OOP with C++ and Java questions
- What is printed? java try { try { throw new RuntimeException("inner"); } finally { System.out.print("inner-finally "); } } catch…
- What is printed? java class A { } class B extends A { } class Test { public static void main(String[] args) { A a = new B(); try { B b =…
- What is printed? java List<String> strings = new ArrayList<>(); List<Integer> ints = new ArrayList<>()…
- What is printed? java Integer a = 127; Integer b = 127; Integer c = 200; Integer d = 200; System.out.println((a == b) + " " + (c == d));
- What is printed? java class Base { public void show() { System.out.print("Base "); } } class Derived extends Base { protected void show()…
- What is printed? java class Base { void greet(Object o) { System.out.print("Object "); } } class Derived extends Base { void greet(String…