I am slightly confused regarding assert.
I have a constructor for a Circular array where the capacity of the array obviously could not be negative as a negative length for an array is invalid. I am aware I could set the value myself if it is invald or throw an exception but I've also seen assert used to prevent invalid input (specifically in C) so I tried following.
Constructor (excluding all the unnecessary parameters that also is initialized):
Note, Message is simply a class that holds a string.
public CircularArray(int capacity)
{
assert capacity > 0 : "Array capacity violated, precondition argument > 0";
elements = new Message[capacity];
}
and if I run it with -ea the assertion is indeed displayed however I still recieve what seems to be an error or trying to initialize an array with an invalid length. Is this how it's supposed to look or do I have to something additional?
Also, since assertions are turned off by default, would it be better to instead throw and exception as follows:
throw new IndexOutOfBoundsException();
To clarify, the terminal output yields:
Exception in thread "main" java.lang.AssertionError: Array capacity violated, precondition argument > 0
at CircularArray.<init>(CircularArray.java:19)
at CircularArray.main(CircularArray.java:98)
Maybe this is the correct output but it felt a bit strange that it clarified what where the errors are generated by specifying what lines of code.