2015-08-04

[Android] 檢查參數Check arguments: Preconditions.checkArgument(), checkNotNull()



http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/Preconditions.html




public static void checkArgument(boolean expression,
                 @Nullable
                 Object errorMessage)

expression應該要是true.
如果expression是false, 就會throw IllegalArgumentException.

Ensures the truth of an expression involving one or more parameters to the calling method.

Parameters:
expression - a boolean expression
errorMessage - the exception message to use if the check fails; will be converted to a string using String.valueOf(Object)

Throws:
IllegalArgumentException - if expression is false

-----------

public static <T> T checkNotNull(T reference,
                 @Nullable
                 Object errorMessage)
Ensures that an object reference passed as a parameter to the calling method is not null.

Parameters:
reference - an object reference
errorMessage - the exception message to use if the check fails; will be converted to a string using String.valueOf(Object)

Returns:
the non-null reference that was validated

Throws:
NullPointerException - if reference is null

-------------

Example:

   /**
    * Returns the positive square root of the given value.
    *
    * @throws IllegalArgumentException if the value is negative
    */
   public static double sqrt(double value) {
     Preconditions.checkArgument(value >= 0.0, "negative value: %s", value);
     // calculate the square root
   }

   void exampleBadCaller() {
     double d = sqrt(-1.0);
   }
In this example, checkArgument throws an IllegalArgumentException to indicate that exampleBadCaller made an error in its call to sqrt.