Question 1
What is the output of the following program?
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
try {
throw new IllegalArgumentException();
} catch (IllegalStateException | IllegalArgumentException e) {
sb.append("C");
} finally {
sb.append("F");
}
System.out.println(sb);
}
}A. C
This omits the finally block, which always runs and appends F after the catch appends C.
B. CFCorrect answer
The IllegalArgumentException matches the multi-catch (appends C), and finally always runs (appends F): CF.
C. F
The catch matches the thrown IllegalArgumentException and appends C before finally appends F.
D. Compilation fails because two exception types share one catch
Multi-catch legally handles either listed type in one block, so it compiles.
Explanation
Multi-catch (Java 7) legally handles either listed type in one block (Compilation fails because two exception types... is wrong). The IllegalArgumentException matches, appending C; finally always runs, appending F: "CF".