Java断言

178 阅读1分钟
public class JavaAssert {
    public static void main(String[] args) {
        int x = 10;
        try {
            assert x <= 0 : "x must >= 0";
        } catch (Exception e) {
            e.printStackTrace();
        }
       
        System.out.println(x);
    }
}

将上述代码编译运行

Javac JavaAssert.java

Java -enableassertions JavaAssert

输出断言异常信息

Exception in thread "main" java.lang.AssertionError: x must >= 0
        at JavaAssert.main(JavaAssert.java:5)