Oracle Certified Associate Java Se 8 Programmer · Free Practice Question Hard
Question 19
Given code of Test.java file:
- package com.udayankhattry.oca;
- public class Test {
- public static void main(String[] args) {
- try { //outer
- try { //inner
- System.out.println(1/0);
- } catch(ArithmeticException e) {
- System.out.println("INNER");
- } finally {
- System.out.println("FINALLY 1");
- }
- } catch(ArithmeticException e) {
- System.out.println("OUTER");
- } finally {
- System.out.println("FINALLY 2");
- }
- }
- }
What will be the result of compiling and executing Test class?
-
A
OUTER
FINALLY 2
-
B
INNER
FINALLY 2
-
C
INNER
FINALLY 1
FINALLY 2
-
D
INNER
FINALLY 1
Reveal correct answer
Correct answer: C
Explanation
System.out.println(1/0); throws ArithmeticException, handler is available in inner catch-block, it executes and prints "INNER" to the console.
Once an exception is handled, no other catch block will get executed unless the exception is re-thrown.
Inner finally-block gets executed and prints "FINALLY 1" to the console.
Rule is finally-block always gets executed, so outer finally-block gets executed and prints "FINALLY 2" to the console.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
