assert关键字用于判断某一条件是否达成,如果达成不进行任何操作,如没有达成会抛出异常。这一关键字可以用来判断一段程序的执行条件和运行结果是否正常,方便debug
assert 有两种语法格式:
1 assert加一个boolean表达式,如果为true不进行操作,如果为false抛出异常AssertionError。 AssertionError属于Error类,和Exception同为Throwable 子类。不过和Exception不同的是Error表达系统级别错误,不可以使用异常处理语句自动处理。
assert boolean;
2 assert表达式后可跟一段字符串,如异常抛出,该字符串会被输出
assert boolean:"expresion";
如图为在归并排序中merge方法里使用的assert
// merge two sorted arrays
public static void merge (Comparable[] a, int low, int high, int mid) {
// check the precondition: a and b are sorted
assert isSorted(a, low, mid):"the left hand side is not sorted";
assert isSorted(a, mid + 1, high):"the right hand side is not sorted";
// copy the array
Comparable[] aux = new Comparable[high + 1];
for (int i = 0; i < aux.length; i++) {
aux[i] = a[i];
}
// merge the two arrays
int j = 0;
int k = mid + 1;
for (int i = 0; i < aux.length; i++) {
if (j > mid) { // left array is exhausted
a[i] = aux[k++];
} else if (k > high) {
a[i] = aux[j++];
} else if (less(aux[j], aux[k])) {
a[i] = aux[j++];
} else {
a[i] = aux[k++];
}
}
// check the final result
assert isSorted(a):"the array is not merged correctly";
}
在该程序中要求归并的两部分预先为有序的,因此在程序开头加入两个assert判断。在程序末尾加入assert判断归并后程序是否有序。如果程序异常,根据assert抛出异常位置可以快速定位错误代码
注意java中assert分开启和关闭状态,只有在开启状态下assert语句才会抛出异常,默认设置为关闭。
在eclipse中开启assert:
选择Run ——> Run Configurations
找到想要修改的类,进入Argument标签页。在VM argument里面加入-ea代表开启assert, -da代表关闭assert



