Given:
public class Main {
public static void main(String[] args) throws Exception {
doSomething();
}
private static void doSomething() throws Exception {
System.out.println("Before if clause");
if (Math.random() > 0.5) {
throw new Exception();
}
System.out.println ("After if clause");
}
Which two are possible outputs?
A.
Before if clause
Exception in thread “main” java.lang.Exception
At Main.doSomething (Main.java:8)
At Main.main (Main.java:3)
B.
Before if clause
Exception in thread “main” java.lang.Exception
At Main.doSomething (Main.java:8)
At Main.main (Main.java:3)
After if clause
C.
Exception in thread “main” java.lang.Exception
At Main.doSomething (Main.java:8)
At Main.main (Main.java:3)
D.
Before if clause
After if clause
Explanation:
The first println statement, System.out.println(“Before if clause”);, will always run.
If Math.Random() > 0.5 then there is an exception. The exception message is displayed and the
program terminates.
If Math.Random() > 0.5 is false, then the second println statement runs as well.
Incorrect answers:
B: The second println statement would not run.
C: The first println statement will always run.