ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Resource {
Resource() {
System.out.print("open ");
throw new RuntimeException("ctor failed");
}
void close() { System.out.print("close "); }
}
public class Main {
public static void main(String[] args) {
try {
Resource r = new Resource();
r.close();
} catch (RuntimeException e) {
System.out.print("caught:" + e.getMessage());
}
}
}- A. open close caught:ctor failed
- B. open caught:ctor failed
- C. Compile-time error: r is used before being fully assigned
- D. close caught:ctor failed
Correct answer: B. open caught:ctor failed
If a constructor throws, the object reference is never produced: r is never assigned, so r.close() never executes. Only "open " prints before the exception is thrown, then it propagates out of the new expression and is caught, printing caught:ctor failed.
More OOP with C++ and Java questions
- What is printed? cpp struct Base { virtual ~Base() { cout << "~Base "; } }; struct Mid : Base { ~Mid() { cout << "~Mid "; } }; struct Leaf…
- What is printed? java class Animal { Animal() { System.out.print(category() + " "); } String category() { return "Animal"; } } class Bird…
- What is printed? cpp struct Base { Base() { cout << "Base "; } Base(const Base&) { cout << "BaseCopy "; } }; struct Derived : Base {…
- What is printed? cpp int f() { std::cout << "f "; return 1; } int g() { std::cout << "g "; return 2; } int a = f(); int b = g(); int…
- What is printed? cpp struct X { int id; X(int i) : id(i) { std::cout << "X" << id << " "; } ~X() { std::cout << "~X" << id << " "; } }…
- What is printed? cpp struct Animal { void speak() { std::cout << "Animal"; } }; struct Dog : Animal { void speak() { std::cout << "Dog"; }…