Difficulty: Easy
Correct Answer: It is sometimes good practice to throw an AssertionError explicitly.
Explanation:
Introduction / Context:
Assertions and AssertionError communicate “this code path should be impossible” conditions. While typical usage is via the assert
keyword, there are cases where throwing AssertionError explicitly is an appropriate way to mark unreachable code.
Given Data / Assumptions:
Concept / Approach:
Evaluate each statement with best practices in mind.
Step-by-Step Solution:
A: True. Example: inside a switch over all enum constants, in the default branch you can throw new AssertionError("Unhandled value: " + v)
. This communicates a bug if reached.B: False. Private/internal methods are good places to use assertions for invariants; the statement claims they “should not,” which is incorrect.C: False. finally always runs after try/catch—even when AssertionError occurs—unless the process terminates abruptly for other reasons.D: False. There is no AssertionException; additionally, catching AssertionError for normal control flow is discouraged.
Verification / Alternative check:
Write a small try/finally that throws new AssertionError(); observe the finally block executes.
Why Other Options Are Wrong:
They misstate best practices or assert facts contrary to Java’s exception semantics.
Common Pitfalls:
Using assertions for public API validation; catching AssertionError to continue execution; assuming finally is skipped on errors.
Final Answer:
It is sometimes good practice to throw an AssertionError explicitly.
Discussion & Comments