nerdexam
Oracle

1Z0-819 · Question #123

Given: public class Test{ private int num = 1; private int div = 0; public void divide() { try { num = num / div; System.out.print("Exception"); } catch (ArithmeticException ae) { num = 100; }…

The correct answer is A. 300. Option A is correct because the finally block always executes and sets num = 300 - overwriting the 100 assigned in the ArithmeticException catch block - before System.out.print(num) runs after the try-catch-finally structure. B ("Exception") is wrong because…

Exception Handling

Question

Given: public class Test{ private int num = 1; private int div = 0; public void divide() { try { num = num / div; System.out.print("Exception"); } catch (ArithmeticException ae) { num = 100; } catch(Exception e) { num = 200; } finally { num = 300; } System.out.print(num); } public static void main(String args[]) { Test test = new Test(); test.divide(); } } What is the output?

Options

  • A300
  • BException
  • C200
  • D100

How the community answered

(25 responses)
  • A
    76% (19)
  • B
    16% (4)
  • C
    4% (1)
  • D
    4% (1)

Explanation

Option A is correct because the finally block always executes and sets num = 300 - overwriting the 100 assigned in the ArithmeticException catch block - before System.out.print(num) runs after the try-catch-finally structure.

B ("Exception") is wrong because System.out.print("Exception") comes after num = num / div, which immediately throws the exception, so that line is never reached. D (100) is a tempting trap: the ArithmeticException catch does set num = 100, but the finally block runs afterward and overwrites it to 300. C (200) is wrong because the more specific ArithmeticException catch fires first; the general Exception catch is only reached if no earlier catch matches.

Memory tip: Think of finally as the last word - it always runs (barring JVM crash or System.exit()), and any assignments inside it will be the final value in scope. On exams, if you see finally touching a variable that's later printed, finally wins.

Topics

#try-catch-finally#finally block semantics#exception handling flow#ArithmeticException

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice