Given the code fragment:
public void infected() {
System.out.print(“before “);
try {
“Pass Any Exam. Any Time.” – www.actualtests.com 94
Oracle 1z0-804 Exam
int i = 1/0;
System.out.print(“try “);
} catch(Exception e) {
System.out.print(“catch “);
throw e;
} finally {
System.out.print(“finally “);
}
System.out.print(“after “);
}
What is the result when infected() is invoked?
A.
before try catch finally after
B.
before catch finally after
C.
before catch after
D.
before catch finally
E.
before catch
Explanation:
The following line throws and exception:
int i = 1/0;This exception is caught by:
catch(Exception e) {
System.out.print(“catch “);
throw e;Lastly, the finally statement is run as the finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
Reference: Java Tutorial,The finally Block
strange.. before catch finally (as ‘run as the finally block always’) and completes this run java.lang.ArithmeticException. So where in answer C is ‘finally’?
If we comment line throw e; (as it is throwing error) the output is
“before catch finally after” So B
The flow is interrupted by the throw new e. So the finally block code is executed and then the exception is thrown.
So the correct asnwer is D and not B.
if you copy the same code in your IDE it will print
before catch finally
compile ist, this ist the output
——————
run:
Exception in thread “main” java.lang.ArithmeticException: / by zero
before catch finally at ocp2.Frage097.infected(Frage097.java:12)
at ocp2.Frage097.main(Frage097.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
—————————
So the correct answer is D
answer D is correct
D
D.
D
D
before catch finally Exception in thread “main” java.lang.ArithmeticException: / by zero
at Test.infected(Test.java:14)
at Test.main(Test.java:6)
d