ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
public class Main {
static void risky(int x) throws Exception {
if (x < 0) throw new Exception("neg");
System.out.print("ok");
}
public static void main(String[] args) {
try {
risky(-1);
} catch (Exception e) {
System.out.print("caught:" + e.getMessage());
} finally {
System.out.print(" done");
}
}
}- A. ok done
- B. caught:neg done
- C. caught:neg
- D. ok caught:neg done
Correct answer: B. caught:neg done
risky(-1) throws before reaching the print("ok") line, so "ok" never prints. The catch block runs, printing caught:neg, and finally always runs afterward, printing " done". Result: caught:neg done.
More OOP with C++ and Java questions
- What is printed? java public class Main { static String f(int x) { try { if (x == 0) throw new ArithmeticException("div0"); return "ok" +…
- What is printed? java class LowBalanceException extends Exception { LowBalanceException(String m) { super(m); } } class Account { double…
- What is printed? java public class Main { public static void main(String[] args) throws Exception { try { method1(); } catch…
- What is printed? java public class Main { static class Resource implements AutoCloseable { public void close() { System.out.print("closed…
- What happens when this is compiled? java class Base { void risky() throws java.io.IOException {} } class Sub extends Base { @Override void…
- What is printed? java public class Main { public static void main(String[] args) { Object o = "text"; try { Integer n = (Integer) o…