ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
class MyChecked extends Exception {
MyChecked(String m) { super(m); }
}
public class Main {
static void risky() throws MyChecked {
throw new MyChecked("fail");
}
public static void main(String[] args) {
try {
risky();
} catch (Exception e) {
System.out.println("Caught: " + e.getMessage());
}
}
}- A. Caught: fail
- B. Compilation error: Exception cannot catch MyChecked
- C. It crashes with an uncaught MyChecked
- D. Compilation error: main must declare throws MyChecked
Correct answer: A. Caught: fail
MyChecked is a checked exception (extends Exception), and risky() correctly declares `throws MyChecked`. A catch(Exception e) clause catches any Exception subtype, including MyChecked, so it's caught and its message printed: "Caught: fail".
More OOP with C++ and Java questions
- Which statement about this code is correct? java class Main { static void risky() { if (Math.random() < 2) throw new…
- What is printed? java public class Main { public static void main(String[] args) { int result = compute(); System.out.println(result); }…
- What is printed? java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); try {…
- What is printed? cpp struct Logger { Logger() { cout << "open "; } ~Logger() noexcept(false) { cout << "close "; throw…
- What is printed? java public class Main { public static void main(String[] args) { try { level1(); } catch (RuntimeException e) {…
- What is printed? java class MyException extends RuntimeException { MyException(String m) { super(m); } } public class Main { public static…