ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
public class Main {
static String f(int x) {
try {
if (x == 0) throw new ArithmeticException("div0");
return "ok" + x;
} catch (ArithmeticException e) {
return "caught:" + e.getMessage();
} finally {
System.out.print("finally ");
}
}
public static void main(String[] args) {
System.out.println(f(0));
}
}- A. finally caught:div0
- B. caught:div0 finally
- C. finally \ncaught:div0 (on separate output then a newline)
- D. Compile-time error: cannot return from both try/catch and have a finally too
Correct answer: A. finally caught:div0
finally runs after the catch block has decided its return value (caught:div0) but before that value is actually handed back to the caller, so "finally " prints first (from inside f), and only then does println print the returned string, caught:div0.
More OOP with C++ and Java questions
- 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…
- What is printed? java public class Main { static int divide(int a, int b) { try { return a / b; } catch (ArithmeticException e) { return…