Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which line is an inappropriate use of an assertion?

public class Sample47
{
    static void process(int[] data)
    {
        try
        {
            assert data.length > 0 : "empty batch";
        }
        catch (AssertionError e)
        {
            System.out.println("continuing anyway");
        }
    }

    public static void main(String[] args)
    {
        process(new int[0]);
    }
}

  • A.process(new int[0]);
  • B.Every line above is correct as written.
  • C.catch (AssertionError e)
  • D.assert data.length > 0 : "empty batch";

Answer: C

Catching AssertionError and carrying on defeats the point of the assertion: the broken invariant is reported, ignored, and the program continues in the state the assertion said was impossible. AssertionError sits under Error precisely to discourage this. If the condition is recoverable it is not an assertion.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.