DEFENSIVE PROGRAMMING WITH KLOJANG CHECK

Throwing a Different Type of Exception

By default, Klojang Check throws an IllegalArgumentException if any of the tests following Check.that(...) fail. To customize this, use the Check.on(...) static factory methods instead. These allow you to change the default exception. The default exception can itself be overridden within the checks themselves. The following example changes the default exception to SQLException, but overrides it for the null check:

public class QueryExecutor {

  private final Query query;

  public QueryExecutor(Query query) {
    this.query = Check.on(SQLException::new, query, "query")
        .is(notNull(), () -> new NullPointerException("query must not be null"))
        .has(Query::where, "where", notEmpty())
        .notHas(Query::offset, "offset", negative())
        .has(Query::limit, "limit", gte(), 10)
        .has(Query::limit, "limit", lte(), 10000)
        .ok();
  }

}

Common Exceptions

Here, too, Klojang Check provides some useful shortcuts via the CommonExceptions class. In the following example, the default exception is now set to IllegalStateException, but the null check still throws a NullPointerException (NPE):

import static org.klojang.check.CommonExceptions.npe;
import static org.klojang.check.CommonExceptions.STATE;

  private final Query query;

  public QueryExecutor(Query query) {
    this.query = Check.on(STATE, query, "query")
        .is(notNull(), npe("query must not be null"))
        .has(Query::where, "where", notEmpty())
        .notHas(Query::offset, "offset", negative())
        .has(Query::limit, "limit", gte(), 10)
        .has(Query::limit, "limit", lte(), 10000)
        .ok();
  }

}