Check Argument Precondition
Google Guava is a java library with lot of utilities and reusable components.
This requires the library guava-10.0.jar to be in classpath.
The following example shows using Preconditions.checkArgument() API.
It throws IllegalArgumentException if the given expression evaluates to false.
package com.bethecoder.tutorials.guava.base_tests;
import com.google.common.base.Preconditions;
public class CheckArgPreTest {
/**
* @param args
*/
public static void main ( String [] args ) {
//Throws IllegalArgumentException - if expression is false
//Preconditions.checkArgument(expression, errorMessage)
/**
* Negative case
*/
try {
Preconditions.checkArgument ( args.length == 2 ,
"This program requires 2 arguments, but found %s" , args.length ) ;
} catch ( IllegalArgumentException e ) {
System.out.println ( e ) ;
}
/**
* Positive case
*/
args = new String [] { "ONE" , "TWO" } ;
Preconditions.checkArgument ( args.length == 2 ,
"This prog requires 2 arguments : %s" , args.length ) ;
System.out.println ( "Thanks for providing valid input" ) ;
}
}
It gives the following output,
java.lang.IllegalArgumentException: This program requires 2 arguments, but found 0
Thanks for providing valid input