2016年11月25日 星期五

[ Java 常見問題 ] What does the “assert” keyword do?

Source From Here 
Question 
What does assert do? For example in the function: 
  1. private static int charAt(String s, int d) {  
  2.     assert d >= 0 && d <= s.length();  
  3.     if (d == s.length()) return -1;  
  4.     return s.charAt(d);  
  5. }  

How-To 
If you launch your program with -enableassertions (or -ea for short) then this statement: 
is equivalent to 
  1. if (!cond)  
  2.     throw new AssertionError();  
If you launch your program without this option, the assert statement will have no effect. For example, assert d >= 0 && d <= s.length();, as posted in your question, is equivalent to: 
  1. if (!(d >= 0 && d <= s.length()))  
  2.     throw new AssertionError();  
Formally, the Java Language Specification: 14.10. The assert Statement says the following: 
14.10. The assert Statement
An assertion is an assert statement containing a boolean expression. An assertion is either enabled or disabled. If the assertion is enabled, execution of the assertion causes evaluation of the boolean expression and an error is reported if the expression evaluates to false. If the assertion is disabled, execution of the assertion has no effect whatsoever.

Where "enabled or disabled" is controlled with the -ea switch and "An error is reported" means that an AssertionError is thrown. 

And finally, a lesser known feature of assert: 
You can append : "Error message" like this: 
  1. assert d != null : "d is null";  
to specify what the error message of the thrown AssertionError should be.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...