Preconditions做爲Guava中異常的前置檢查,提供了一系列方法。從源碼的實現中能夠看出,全部的方法都知足如下形式(除format()方法之外)。express
if (!status) { throw new xxException(); }
例如:app
public static void checkArgument(boolean expression) { if (!expression) { throw new IllegalArgumentException(); } }
源碼實現比較簡單,沒有太多須要細說。其中有個方法,format()方法,不一樣於String.format(),源碼實現以下:測試
static String format(String template, @Nullable Object... args) { template = String.valueOf(template); // null -> "null" // start substituting the arguments into the '%s' placeholders StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); int templateStart = 0; int i = 0; while (i < args.length) { int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template.substring(templateStart, placeholderStart));// 獲取%s以前的字符串進行拼接 builder.append(args[i++]);//替換%s templateStart = placeholderStart + 2; } builder.append(template.substring(templateStart));//拼接以後的字符串
// 若是還有爲使用的args。直接在[]內顯示出來 // if we run out of placeholders, append the extra args in square braces if (i < args.length) { builder.append(" ["); builder.append(args[i++]); while (i < args.length) { builder.append(", "); builder.append(args[i++]); } builder.append(']'); } return builder.toString();
與Preconditions相似的功能類,Verify提供了相似的方法,JDK原生的Assert也提供了相似的方法,使用方式遵循一下原則ui
《Effective Java》中58條對CheckedException、RuntimeException和Error使用方式作了詳細的說明:google