Automated IllegalArgumentException message?

I always check the arguments of public functions and throw exceptions when something's wrong. (For private helpers I use assertions).

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 just the negation of the statement

a < 0 || a >= b

.

It also often happens that I rename the variable with refactoring (in eclipse) and then the message does not reflect the changes. 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 raise an IllegalArgumentException with a message like

"violated argument assertion: a >= 0 && a < b."

In C you could write a macro (actually in C assert is just a macro). Is there a simple way to do something like this in java?

Thank you!


In the C language you cannot use macros to do this, but in cpp (the C preprocessor) you can :-) If you really want to do so there is nothing that restricts you from running cpp on your java source before it gets compiled. That would let you use cpp style macros (you might need to strip the lines starting with #line from the cp output.)

To reproduce the conditional in the exception is IMHO including too much implementation detail. If your exception message describes the violation in the contract in terms of the contract (for instance "no parent object given", "amount cannot be negative") you don't need to change it every time the condition changes.

链接地址: http://www.djcxy.com/p/76228.html

上一篇: 番石榴前提条件checkNull,checkArgument

下一篇: 自动IllegalArgumentException消息?