Question
What does assert do? For example in the function:
- private static int charAt(String s, int d) {
- assert d >= 0 && d <= s.length();
- if (d == s.length()) return -1;
- return s.charAt(d);
- }
How-To
If you launch your program with -enableassertions (or -ea for short) then this statement:
- assert cond;
- if (!cond)
- throw new AssertionError();
- if (!(d >= 0 && d <= s.length()))
- throw new AssertionError();
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:
- assert d != null : "d is null";
沒有留言:
張貼留言