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

posted @ 2021-08-04 17:17  talentzemin  阅读(97)  评论(0编辑  收藏  举报