1. 程式人生 > 其它 >Assert in C#&Java

Assert in C#&Java

Assert是什麼?

斷言(Assertion)是一種除錯程式的方式。

C#中的Assert

In a debug compilation, Assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
If you compile in Release, all Debug.Assert's are automatically left out.

ref: https://stackoverflow.com/questions/163538/c-sharp-what-does-the-assert-method-do-is-it-still-useful

Java中的Assert

Assertions (by way of the assert keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code.

code

 public static void main(String[] args) {
      String name = null;
      assert (name != null) : "name is null, maybe a bug";
      System.out.println(name);
   }

JVM start args

"vmArgs":"-ea" //enable assertions

result

Exception in thread "main" java.lang.AssertionError: name is null, maybe a bug
        at App.main(App.java:7)

ref:https://stackoverflow.com/questions/2758224/what-does-the-java-assert-keyword-do-and-when-should-it-be-used