为什么程序没有显示任何 AssertionError?

Why is the program not showing any AssertionError?

我已经执行了这样的代码:java -ea HelloWorld 以及显示 AssertionError 的其他代码,但是对于这个特定的代码,我没有收到任何 AssertionError。

public class HelloWorld{

     public static void main(String []args){
         boolean b=true;
         assert(b==true);
         b=false;     
     }
}

您正在断言 b==true,它在断言执行时执行。如果断言为假,则抛出 AssertionError。来自 Oracle documentation:

Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors

它可以通过两种不同的方式应用:

The assertion statement has two forms. The first, simpler form is:

assert Expression1 ;

where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.

The second form of the assertion statement is:

assert Expression1 : Expression2 ;

where:

  • Expression1 is a boolean expression.
  • Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)

Use this version of the assert statement to provide a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's detail message.

如果您还没有弄清楚 Java 断言是如何工作的:

断言 表达式 : message_if_not_true

因此,如果您的断言评估为 False,您将收到一条错误消息。

你在做什么:

assert(b == true) 

不会导致 assertionError 因为 b 在上一行被设置为 true。检查 Java Oracle 文档中的断言。