Assertions: Difference between revisions
→{{header|Java}}
(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 />
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 />
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 />
The <code>assert</code> syntax is as follows.
assert valueA == valueB;
</syntaxhighlight>
It is essentially a boolean expression, which if not met, will throw an <code>AssertionError</code> exception.<br />
It is effectively shorthand for the following code.
<syntaxhighlight lang="java">
if (valueA != valueB)
throw new AssertionError();
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">
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}}==
|