I always check the arguments of public functions and throw exceptions when something is wrong. (For private assistants I use statements).
Like this:
if( a < 0 || a >= b ) throw new IllegalArgumentException("'a' must be greater or equal to 0 and smaller than b ");
But it always annoys me to write these error messages. The message seems redundant to me, as the message is simply a denial of the statement
a < 0 || a >= b
.
It also often happens that I rename a variable with refactoring (in eclipse), and then the message does not reflect the change. Or I change the conditions and forget to change the messages.
It would be great if I could write something like:
assertArgument(a >= 0 && a < b);
This should throw an IllegalArgumentException with a message like
"violated argument assertion: a >= 0 && a < b."
In C, you can write a macro (in fact, only a macro in C assert). Is there an easy way to do something like this in java?
Thanks!
java assertions illegalargumentexception
Dario seidl
source share