Assertions: Difference between revisions

(RPL: add section)
Line 835:
 
=={{header|Java}}==
In Java, the <code>assert</code> keyword is used to place an assertive statement within the program.<br />
<syntaxhighlight lang="java5">public class Assertions {
A 'false' assertion will stop the program, as opposed to pausing, as with some other languages.<br />
 
It's worth noting that assertions were created specifically for the development and debugging of the program, and are not intended to be part of the control-flow.<br />
public static void main(String[] args) {
Some JVM implementations will have assertions disabled by default, so you'll have to enable them at the command line, switch '<tt>-ea</tt>' or '<tt>-enableassertions</tt>'.<br />
int a = 13;
Inversely, to disable them, use '<tt>-da</tt>', or '<tt>-disableassertions</tt>'.<br />
 
For more information see [https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html Oracle - Programming With Assertions].<br /><br />
// ... some real code here ...
The <code>assert</code> syntax is as follows.
 
<syntaxhighlight lang="java5java">public class Assertions {
assert a == 42;
assert valueA == valueB;
// Throws an AssertionError when a is not 42.
</syntaxhighlight>
 
It is essentially a boolean expression, which if not met, will throw an <code>AssertionError</code> exception.<br />
assert a == 42 : "Error message";
It is effectively shorthand for the following code.
// Throws an AssertionError when a is not 42,
<syntaxhighlight lang="java">
// with "Error message" for the message.
if (valueA != valueB)
// The error message can be any non-void expression.
throw new AssertionError();
}
}</syntaxhighlight>
You can also specify a <code>String</code> with the assertion, which will be used as the exception's detail-message, which is displayed with the stack-trace upon error.
 
<syntaxhighlight lang="java">
Note: assertion checking is disabled by default when you run your program with the <tt>java</tt> command. You must provide the <tt>-ea</tt> (short for <tt>-enableassertions</tt>) flag in order to enable them.
assert valueA == valueB : "valueA is not 42";
</syntaxhighlight>
<pre>
Exception in thread "main" java.lang.AssertionError: valueA is not 42
at Example.main(Example.java:5)
</pre>
You can also specify any other Object or primitive data type as a message.<br />
If it's an object, the <code>toString</code> method will be used as the message.
<syntaxhighlight lang="java">
assert valueA == valueB : valueA;
</syntaxhighlight>
 
=={{header|JavaScript}}==
118

edits