Automatic message about the exclusion of illegal messages?

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!

+6
java assertions illegalargumentexception
source share
1 answer

In C, you cannot use macros for this, but in cpp (C preprocessor) you can :-) If you really want to, there is nothing to limit you from running cpp on your java source before it compiles. This will allow you to use cpp style macros (you may need to split the lines starting with #line with cp output.)

To reproduce a conditional expression in an exception, IMHO includes too many implementation details. If your exception message describes a breach of the contract in terms of the contract (for example, "parent is not specified", "the amount cannot be negative"), you do not need to change it every time the condition is changed.

+3
source share

All Articles