Question

I want to do null checks for my method arguments, like parameters should not be null. Is it okay to use something like this assertNotNull("Map should not be null", filePaths); in my Java code? I'm trying to avoid

if(filePaths == null){
  throw new IllegalArgumentException("Maps cannot be null");
}

just to keep my code clean from all those null checks. I know I can write a Validator class of my own and have overloaded notNull methods but is there something existing and simple to use to not re-invent the wheel.

The only drawback I see of using JUnit Assert is that it throws AssertionError and not IllegalArgumentException and so forth.

Was it helpful?

Solution 2

No, it is not OK to use it. The JUnit assert methods throw an AssertionError. It's not a good idea to throw Error in production code. From the javadoc:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it. A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.

OTHER TIPS

If you use Java 7+, you can use:

Objects.requireNonNull(filePaths, "Map should not be null");

Also with a null argument, I would expect a NullPointerException or an IllegalArgumentException, but not an AssertionError.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top