Assertions: Difference between revisions

Add Ecstasy example
m (syntax highlighting fixup automation)
(Add Ecstasy example)
(14 intermediate revisions by 11 users not shown)
Line 13:
{{trans|Python}}
 
<syntaxhighlight lang="11l">V a = 5
assert(a == 42)
assert(a == 42, ‘Error message’)</syntaxhighlight>
 
=={{header|68000 Assembly}}==
<syntaxhighlight lang="68000devpac">CMP.L #42,D0
BEQ continue
ILLEGAL ;causes an immediate jump to the illegal instruction vector.
Line 26:
=={{header|Ada}}==
Using pragma Assert:
<syntaxhighlight lang="ada">pragma Assert (A = 42, "Oops!");</syntaxhighlight>
The behavior of pragma is controlled by pragma Assertion_Policy. Another way is to use the predefined package Ada.Assertions:
<syntaxhighlight lang="ada">with Ada.Assertions; use Ada.Assertions;
...
Assert (A = 42, "Oops!");</syntaxhighlight>
The procedure Assert propagates Assertion_Error when condition is false.
Since Ada 2012 one may also specify preconditions and post-conditions for a subprogram.
<syntaxhighlight lang="ada">procedure Find_First
(List : in Array_Type;
Value : in Integer;
Line 46:
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">integer x;
 
x = 41;
Line 70:
 
In [[ELLA ALGOL 68]] the ASSERT is implemented as an operator in the ''environment'' prelude:
<syntaxhighlight lang="algol68">OP ASSERT = (VECTOR [] CHAR assertion,BOOL valid) VOID:
IF NOT valid
THEN type line on terminal(assertion);
Line 76:
FI;</syntaxhighlight>
And can be "USEd" as follows:
<syntaxhighlight lang="algol68">PROGRAM assertions CONTEXT VOID
USE standard,environment
BEGIN
Line 87:
Assertions were added to the 1972 version of Algol W. If the tested condition is false, the program terminates. In the following, the write does not get executed.
 
<syntaxhighlight lang="algolw">begin
integer a;
a := 43;
Line 96:
=={{header|Apex}}==
Asserts that the specified condition is true. If it is not, a fatal error is returned that causes code execution to halt.
<syntaxhighlight lang="apex">
String myStr = 'test;
System.assert(myStr == 'something else', 'Assertion Failed Message');
Line 102:
 
Asserts that the first two arguments are the same. If they are not, a fatal error is returned that causes code execution to halt.
<syntaxhighlight lang="apex">
Integer i = 5;
System.assertEquals(6, i, 'Expected 6, received ' + i);
Line 108:
 
Asserts that the first two arguments are different. If they are the same, a fatal error is returned that causes code execution to halt.
<syntaxhighlight lang="apex">
Integer i = 5;
System.assertNotEquals(5, i, 'Expected different value than ' + i);
Line 116:
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">a: 42
ensure [a = 42]</syntaxhighlight>
 
Line 122:
=== Exceptions ===
{{works with|AutoHotkey_L}}
<syntaxhighlight lang=AHK"ahk">a := 42
Assert(a > 10)
Assert(a < 42) ; throws exception
Line 131:
}</syntaxhighlight>
=== Legacy versions ===
<syntaxhighlight lang=AutoHotkey"autohotkey">if (a != 42)
{
OutputDebug, "a != 42" ; sends output to a debugger if connected
Line 142:
AWK doesn't have a built-in assert statement. It could be simulated using a user-defined assert() function defined as below. The BEGIN section shows some examples of successful and failed "assertions".
 
<syntaxhighlight lang="awk">
BEGIN {
meaning = 6 * 7
Line 172:
 
=={{header|Axe}}==
<syntaxhighlight lang="axe">A=42??Returnʳ</syntaxhighlight>
 
=={{header|BaConBASIC}}==
==={{header|BaCon}}===
<syntaxhighlight lang=qbasic>' Assertions
<syntaxhighlight lang="qbasic">' Assertions
answer = assertion(42)
PRINT "The ultimate answer is indeed ", answer
Line 220 ⟶ 221:
41</pre>
 
==={{header|BASIC256}}===
{{works with|BASIC256|2.0.0.11}}
<syntaxhighlight lang=BASIC256"basic256">
subroutine assert (condition, message)
if not condition then print "ASSERTION FAIED: ";message: throwerror 1
Line 231 ⟶ 232:
</syntaxhighlight>
 
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> PROCassert(a% = 42)
END
Line 255 ⟶ 256:
 
=={{header|Brat}}==
<syntaxhighlight lang="brat">squish import :assert :assertions
 
assert_equal 42 42
Line 261 ⟶ 262:
 
=={{header|C}}==
<syntaxhighlight lang="c">#include <assert.h>
 
int main(){
Line 273 ⟶ 274:
 
There is no mechanism to add a custom "message" with your assertion, like in other languages. However, there is a "trick" to do this, by simply logical-AND-ing your condition with a string constant message, like in the following. Since a string constant is guaranteed to be non-NULL (and hence evaluated as True), and since AND-ing with True is an identity operation for a boolean, it will not alter the behavior of the assertion, but it will get captured in the debug message that is printed:
<syntaxhighlight lang="c">assert(a == 42 && "Error message");</syntaxhighlight>
This trick only works with messages written directly in the source code (i.e. cannot be a variable or be computed), however, since the assertion message is captured by the macro at compile-time.
 
Line 289 ⟶ 290:
Calls to methods of the Debug class are only compiled when the DEBUG compiler constant is defined, and so are intended for asserting invariants in internal code that could only be broken because of logic errors. Calls to methods of the Trace class similarly require the TRACE constant, which, however, is defined by default for both debug and release builds in Visual Studio projects—trace assertions can thus be used for various logging purposes in production code.
 
<syntaxhighlight lang="csharp">using System.Diagnostics; // Debug and Trace are in this namespace.
 
static class Program
Line 311 ⟶ 312:
}</syntaxhighlight>
 
<syntaxhighlight lang="vbnet">Imports System.Diagnostics
' Note: VB Visual Studio projects have System.Diagnostics imported by default,
' along with several other namespaces.
Line 357 ⟶ 358:
 
Subscribing an instance involves adding the following line to the beginning of Main() (with a semicolon in C#, of course ;)
<syntaxhighlight lang="vbnet">Trace.Listeners.Add(new ConsoleTraceListener())</syntaxhighlight>
 
=={{header|C++}}==
{{trans|C}}
<syntaxhighlight lang="cpp">#include <cassert> // assert.h also works
 
int main()
Line 374 ⟶ 375:
 
=={{header|Clojure}}==
<syntaxhighlight lang=Clojure"clojure">
(let [i 42]
(assert (= i 42)))
Line 380 ⟶ 381:
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">(let ((x 42))
(assert (and (integerp x) (= 42 x)) (x)))</syntaxhighlight>
 
=={{header|Component Pascal}}==
Works with BlackBox Component Builder
<syntaxhighlight lang="oberon2">
MODULE Assertions;
VAR
Line 422 ⟶ 423:
Crystal doesn't have an assert statement. the <code>spec</code> module provides a testing DSL, but a simple assert can be created with a function or macro.
 
<syntaxhighlight lang="ruby">class AssertionError < Exception
end
 
Line 432 ⟶ 433:
 
=={{header|D}}==
<syntaxhighlight lang="d">import std.exception: enforce;
 
int foo(in bool condition) pure nothrow
Line 471 ⟶ 472:
=={{header|Dart}}==
=== Assert ===
<syntaxhighlight lang="javascript">
main() {
var i = 42;
Line 480 ⟶ 481:
=== Expect ===
Testing assertions can be done using the test and expect functions in the test package
<syntaxhighlight lang="d">import 'package:test/test.dart';
 
main() {
Line 497 ⟶ 498:
=={{header|Delphi}}==
 
<syntaxhighlight lang=Delphi"delphi">Assert(a = 42);</syntaxhighlight>
 
If an assertion fails, EAssertionFailed exception is raised.
Line 503 ⟶ 504:
The generation of assertion code can be disabled by compiler directive
 
<syntaxhighlight lang=Delphi"delphi">{$ASSERTIONS OFF}</syntaxhighlight>
 
Here is a simple console demo app which raises and handles assertion exception:
 
<syntaxhighlight lang=Delphi"delphi">program TestAssert;
 
{$APPTYPE CONSOLE}
Line 531 ⟶ 532:
=={{header|DWScript}}==
Simple assertion, with a custom (optional) message
<syntaxhighlight lang=Delphi"delphi">Assert(a = 42, 'Not 42!');</syntaxhighlight>
Other specialized assertions can be used in contracts, for instance this function check that the parameter (passed by reference ofr the purpose of illustration) is 42 when entering the function and when leaving the function
<syntaxhighlight lang=Delphi"delphi">procedure UniversalAnswer(var a : Integer);
require
a = 42;
Line 545 ⟶ 546:
Dyalect has a built-in "assert" function:
 
<syntaxhighlight lang="dyalect">var x = 42
assert(42, x)</syntaxhighlight>
 
Line 554 ⟶ 555:
E does not have the specific feature of assertions which may be disabled by a global option. But it does have a utility to throw an exception if a condition is false:
 
<syntaxhighlight lang="e">require(a == 42) # default message, "Required condition failed"
 
require(a == 42, "The Answer is Wrong.") # supplied message
Line 561 ⟶ 562:
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="lisp">
(assert (integer? 42)) → #t ;; success returns true
 
Line 575 ⟶ 576:
=={{header|ECL}}==
 
<syntaxhighlight lang="text">
ASSERT(a = 42,'A is not 42!',FAIL);</syntaxhighlight>
 
=={{header|Ecstasy}}==
Ecstasy assertions raise an exception on failure. The default <code>assert</code> statement raises an <code>IllegalState</code>, but there are a few varieties:
 
{| class="wikitable"
! statement !! exception class
|-
| <code>assert</code> || <code>IllegalState</code>
|-
| <code>assert:arg</code> || <code>IllegalArgument</code>
|-
| <code>assert:bounds</code> || <code>OutOfBounds</code>
|-
| <code>assert:TODO</code> || <code>NotImplemented</code>
|}
 
The above assertions are always evaluated when they are encountered in the code; in other words, assertions are always enabled. There are three additional forms that allow developers to alter this behavior:
 
{| class="wikitable"
! statement !! exception class
|-
| <code>assert:test</code> || Evaluate when in "test" mode, but never evaluate in production mode
|-
| <code>assert:once</code> || Evaluate the assertion only the first time it is encountered
|-
| <code>assert:rnd(</code><i>n</i><code>)</code> || Statistically sample, such that the assertion is evaluated 1 out of every <code>n</code> times that the assertion is encountered
|}
 
This example will always evalaute (and fail) the assertion:
 
<syntaxhighlight lang="ecstasy">
module test {
void run() {
Int x = 7;
assert x == 42;
}
}
</syntaxhighlight>
 
Note that the text of the assertion expression and the relevant values are both included in the exception message:
 
{{out}}
<pre>
x$ xec test
 
2024-04-24 17:29:23.427 Service "test" (id=1) at ^test (CallLaterRequest: native), fiber 4: Unhandled exception: IllegalState: "x == 42": x=7
at run() (test.x:4)
at ^test (CallLaterRequest: native)
</pre>
 
=={{header|Eiffel}}==
Line 584 ⟶ 634:
 
File called main.e:
<syntaxhighlight lang="eiffel">class MAIN
creation main
feature main is
Line 597 ⟶ 647:
end</syntaxhighlight>
Another file called test.e:
<syntaxhighlight lang="eiffel">class TEST
feature assert(val: INTEGER) is
require
Line 607 ⟶ 657:
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">ExUnit.start
 
defmodule AssertionTest do
Line 639 ⟶ 689:
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(require 'cl-lib)
(let ((x 41))
(cl-assert (= x 42) t "This shouldn't happen"))</syntaxhighlight>
Line 645 ⟶ 695:
=={{header|Erlang}}==
Erlang doesn't have an assert statement. However, it is single assignment, and its assignment operator won't complain if you reassign the exact same value to an existing variable but will throw an exception otherwise.
<syntaxhighlight lang="erlang">1> N = 42.
42
2> N = 43.
Line 659 ⟶ 709:
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">type fourty_two(integer i)
return i = 42
end type
Line 669 ⟶ 719:
=={{header|F_Sharp|F#}}==
F# provides an ''assert'' function that is only enabled when the program is compiled with ''DEBUG'' defined. When an assertion fails, a dialog box is shown with the option to enter the debugger.
<syntaxhighlight lang="fsharp">let test x =
assert (x = 42)
 
Line 679 ⟶ 729:
Throw an exception if the value on the top of the stack is not equal to 42:
 
<syntaxhighlight lang="factor">USING: kernel ;
42 assert=</syntaxhighlight>
 
Line 686 ⟶ 736:
 
This implementation evaluates the expression given to the function and displays a message if it evaluates to false.
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
DECLARE asserter
Line 706 ⟶ 756:
 
=={{header|Forth}}==
<syntaxhighlight lang="fsharp">variable a
: assert a @ 42 <> throw ;
 
Line 712 ⟶ 762:
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
' requires compilation with -g switch
 
Line 727 ⟶ 777:
 
=={{header|GAP}}==
<syntaxhighlight lang="gap"># See section 7.5 of reference manual
 
# GAP has assertions levels. An assertion is tested if its level
Line 749 ⟶ 799:
=={{header|Go}}==
Assertions are a feature [http://golang.org/doc/go_faq.html#assertions consciously omitted] from Go. For cases where you want feedback during development, the following code should provide a similar purpose. While it is simply an if statement and a panic, the technique does have some properties typical of assertions. For one, the predicate of an if statement in Go is required to be of boolean type. Specifically, ints are not tacitly tested for zero, pointers are not tested for nil: the expression must be boolean, as the WP article mentions is typical of assertions. Also, it provides a good amount of information should the predicate evaluate to true. First, a value of any type can be passed to the panic, and by default is displayed, followed by a stack trace which includes the location of the panic in the source code&mdash;function name, file name, and line number.
<syntaxhighlight lang="go">package main
 
func main() {
Line 773 ⟶ 823:
 
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">def checkTheAnswer = {
assert it == 42 : "This: " + it + " is not the answer!"
}</syntaxhighlight>
 
Test program:
<syntaxhighlight lang="groovy">println "before 42..."
checkTheAnswer(42)
println "before 'Hello Universe'..."
Line 791 ⟶ 841:
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import Control.Exception
 
main = let a = someValue in
Line 799 ⟶ 849:
=={{header|Icon}} and {{header|Unicon}}==
 
<syntaxhighlight lang=Icon"icon">...
runerr(n,( expression ,"Assertion/error - message.")) # Throw (and possibly trap) an error number n if expression succeeds.
...
Line 807 ⟶ 857:
There are no 'assertions', which can be turned on/off by the compiler. We can emulate them by prefixing a stop statement with a check on a global variable:
 
<syntaxhighlight lang=Icon"icon">
$define DEBUG 1 # this allows the assertions to go through
 
Line 831 ⟶ 881:
 
=={{header|J}}==
<syntaxhighlight lang="j"> assert n = 42</syntaxhighlight>
 
=={{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="java">
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}}==
<syntaxhighlight lang=javaScript"javascript">
function check() {
try {
Line 936 ⟶ 997:
 
'''assert.jq'''
<syntaxhighlight lang="jq">def assert(exp; $msg):
def m: $msg | if type == "string" then . else [.[]] | join(":") end;
if env.JQ_ASSERT then
Line 957 ⟶ 1,018:
</syntaxhighlight>
'''Example'''
<syntaxhighlight lang="jq">
# File: example.jq
# This example assumes the availability of the $__loc__ function
Line 984 ⟶ 1,045:
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">const x = 5
# @assert macro checks the supplied conditional expression, with the expression
Line 1,000 ⟶ 1,061:
Kotlin supports Jva-style assertions. These need to be enabled using java's -ea option for an <code>AssertionError</code> to be thrown when the condition is false. An assertion should generally never fire, and throws an <code>Error</code>. <code>Error</code>s are seldom used in Kotlin (and much less assertions), as they represent catastrophic issues with the program, such as classes failing to load. These are usually only ever raised by the JVM itself, rather than actual user code.
 
<syntaxhighlight lang="kotlin">fun main() {
val a = 42
assert(a == 43)
Line 1,013 ⟶ 1,074:
A more Kotlin idiomatic approach to checks are the <code>require</code> (and <code>requireNotNull</code>) to check arguments, and the <code>check</code> (and <code>checkNotNull</code>), and <code>error</code> to check state. The former is mostly meant for checking input, and will throw <code>IllegalArgumentException</code>s, whereas the later is meant for state-checking, and will throw <code>IllegalStateException</code>s
 
<syntaxhighlight lang="kotlin">fun findName(names: Map<String, String>, firstName: String) {
require(names.isNotEmpty()) { "Please pass a non-empty names map" } // IllegalArgumentException
val lastName = requireNotNull(names[name]) { "names is expected to contain name" } // IllegalArgumentException
Line 1,023 ⟶ 1,084:
 
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">local(a) = 8
fail_if(
#a != 42,
Line 1,036 ⟶ 1,097:
but we could break program if condition is not met.
We can even make it spell "AssertionFailed". In a way.
<syntaxhighlight lang="lb">
a=42
call assert a=42
Line 1,066 ⟶ 1,127:
=={{header|Lingo}}==
Lingo has no assert statement, but the abort command (that exits the full call stack) allows to implement something like it as global function:
<syntaxhighlight lang="lingo">-- in a movie script
on assert (ok, message)
if not ok then
Line 1,085 ⟶ 1,146:
 
=={{header|Lisaac}}==
<syntaxhighlight lang=Lisaac"lisaac">? { n = 42 };</syntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">a = 5
assert (a == 42)
assert (a == 42,'\''..a..'\' is not the answer to life, the universe, and everything')</syntaxhighlight>
Line 1,097 ⟶ 1,158:
Trapping error may leave current stack of values with values so if we have above try {} a block of Stack New {} then we get old stack after exit of Stack New {} (this statement hold current stack, attach a new stack of value, and at the exit restore old stack). Another way is to use Flush which clear stack. Statement Flush Error clear all level of error information.
 
=====Making own logging for errors=====
 
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module Assert {
\\ This is a global object named Rec
Line 1,120 ⟶ 1,181:
}
Module SaveIt {
.lastfilename$<=replace$("/", "-","Err"+date$(today)+timestr$(now, "-nn-mm")+".err")
Save.Doc .doc$,.lastfilename$
}
Line 1,138 ⟶ 1,199:
Try {
Test
Report "Run this"
Error "Hello"
Line 1,159 ⟶ 1,221:
}
Assert
</syntaxhighlight>
=====Using Assert Statement=====
Assert is a statement from 10th version (the previous example run because we can locally alter a statement using a module with same name).
 
When we run a program by applying a file gsb as argument the escape off statement applied by default. So asserts didn't work for programs. If we open the M2000 environment and then load a program, then the asserts work (or not if we use escape off). So this example can show x, from print x if we have x=10, but can show 0 if we run it with escape off statement.
 
<syntaxhighlight lang="m2000 interpreter">
// escape off // using escape off interpreter skip assert statements
x=random(0, 1)*10
try {
assert x=10
print x
}
</syntaxhighlight>
 
=={{header|Maple}}==
(Taken from Lua, above.)
<syntaxhighlight lang=Maple"maple">a := 5:
ASSERT( a = 42 );
ASSERT( a = 42, "a is not the answer to life, the universe, and everything" );</syntaxhighlight>
Line 1,169 ⟶ 1,244:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
 
<syntaxhighlight lang=Mathematica"mathematica">Assert[var===42]</syntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
 
<syntaxhighlight lang=MATLAB"matlab">assert(x == 42,'x = %d, not 42.',x);</syntaxhighlight>
 
Sample Output:
<syntaxhighlight lang=MATLAB"matlab">x = 3;
assert(x == 42,'Assertion Failed: x = %d, not 42.',x);
??? Assertion Failed: x = 3, not 42.
Line 1,185 ⟶ 1,260:
Metafont has no really an assert built in, but it can easily created:
 
<syntaxhighlight lang="metafont">def assert(expr t) = if not (t): errmessage("assertion failed") fi enddef;</syntaxhighlight>
 
This <code>assert</code> macro uses the <code>errmessage</code> built in to show the "error". The
Line 1,192 ⟶ 1,267:
Usage example:
 
<syntaxhighlight lang="metafont">n := 41;
assert(n=42);
message "ok";</syntaxhighlight>
Line 1,209 ⟶ 1,284:
=={{header|Modula-3}}==
<code>ASSERT</code> is a pragma, that creates a run-time error if it returns <code>FALSE</code>.
<syntaxhighlight lang="modula3"><*ASSERT a = 42*></syntaxhighlight>
 
Assertions can be ignored in the compiler by using the <code>-a</code> switch.
 
=={{header|Nanoquery}}==
<syntaxhighlight lang=Nanoquery"nanoquery">a = 5
assert (a = 42)</syntaxhighlight>
 
=={{header|Nemerle}}==
A basic assertion uses the <tt>assert</tt> keyword:
<syntaxhighlight lang=Nemerle"nemerle">assert (foo == 42, $"foo == $foo, not 42.")</syntaxhighlight>
Assertion violations throw an <tt>AssertionException</tt> with the line number where the assertion failed and the message provided as the second parameter to assert.
 
Nemerle also provides macros in the <tt>Nemerle.Assertions</tt> namespace to support preconditions, postconditions and class invariants:
<syntaxhighlight lang=Nemerle"nemerle">using Nemerle.Assertions;
 
class SampleClass
Line 1,248 ⟶ 1,323:
* it is a pattern, numbers match themselves exactly, other patterns that would match: <tt>Int</tt>, <tt>0..100</tt>, <tt>Any</tt>
 
<syntaxhighlight lang=NGS"ngs">a = 42
 
assert(a==42)
Line 1,257 ⟶ 1,332:
=={{header|Nim}}==
In Nim there are two main ways to check assertions.
<syntaxhighlight lang=Nim"nim">var a = 42
assert(a == 42, "Not 42!")</syntaxhighlight>
This first kind of assertion may be disabled by compiling with --assertions:off or -d:danger.
<syntaxhighlight lang=Nim"nim">var a = 42
doAssert(a == 42, "Not 42!")</syntaxhighlight>
This second kind of assertion cannot be disabled.
 
=={{header|Nutt}}==
<syntaxhighlight lang="Nutt">
module main
 
demand 5==42
 
end
</syntaxhighlight>
 
=={{header|Oberon-2}}==
Oxford Oberon-2
<syntaxhighlight lang="oberon2">
MODULE Assertions;
VAR
Line 1,284 ⟶ 1,368:
=={{header|Objeck}}==
If variable is not equal to 42 a stack trace is generated and the program is halts.
<syntaxhighlight lang="objeck">class Test {
function : Main(args : String[]) ~ Nil {
if(args->Size() = 1) {
Line 1,296 ⟶ 1,380:
=={{header|Objective-C}}==
For use within an Objective-C method:
<syntaxhighlight lang="objc">NSAssert(a == 42, @"Error message");</syntaxhighlight>
 
If you want to use formatting arguments, you need to use the assertion macro corresponding to your number of formatting arguments:
<syntaxhighlight lang="objc">NSAssert1(a == 42, @"a is not 42, a is actually %d", a); # has 1 formatting arg, so use NSAssert"1"</syntaxhighlight>
 
Within a regular C function you should use <code>NSCAssert</code> or <code>NSCAssert''N''</code> instead.
Line 1,306 ⟶ 1,390:
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let a = get_some_value () in
assert (a = 42); (* throws Assert_failure when a is not 42 *)
(* evaluate stuff to return here when a is 42 *)</syntaxhighlight>
Line 1,320 ⟶ 1,404:
If an assertion is ko (and if oforth is launched using --a), an exception is raised.
 
<syntaxhighlight lang=Oforth"oforth">: testInteger(n, m)
assert: [ n isInteger ]
assert: [ n 42 == ]
Line 1,336 ⟶ 1,420:
 
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(define i 24)
 
(assert i ===> 42)
; or
(assert (= i 42))
</syntaxhighlight>
{{Out}}
Line 1,350 ⟶ 1,436:
assertion error:
i must be 42
> (assert (= i 42))
>
assertion error:
(= i 42) is not a true
</pre>
 
Line 1,356 ⟶ 1,444:
Oz does not have an assert statement. But if different values are assigned to the same dataflow variable, an exception will be thrown (similar to Erlang).
 
<syntaxhighlight lang="oz">declare
proc {PrintNumber N}
N=42 %% assert
Line 1,378 ⟶ 1,466:
PARI can use any of the usual C methods for making assertions. GP has no built-in assertions.
{{trans|C}}
<syntaxhighlight lang=C"c">#include <assert.h>
#include <pari/pari.h>
 
Line 1,391 ⟶ 1,479:
 
More common is the use of <code>pari_err_BUG</code> in such cases:
<syntaxhighlight lang=C"c">if (!equalis(a, 42)) pari_err_BUG("this_function_name (expected a = 42)");</syntaxhighlight>
 
=={{header|Pascal}}==
Line 1,399 ⟶ 1,487:
While not exactly an assertion, a common Perl idiom is to use <code>or die</code> to throw an exception when a certain statement is false.
 
<syntaxhighlight lang="perl">print "Give me a number: ";
chomp(my $a = <>);
 
Line 1,410 ⟶ 1,498:
 
This idiom is typically used during file operations:
<syntaxhighlight lang="perl">open my $fh, '<', 'file'
or die "Cannot open file: $!\n"; # $! contains the error message from the last error</syntaxhighlight>
It is not needed whith the "autodie" pragma:
<syntaxhighlight lang="perl">use autodie;
open my $fh, '<', 'file'; # automatically throws an exception on failure</syntaxhighlight>
 
Some third-party modules provide other ways of using assertions in Perl:
<syntaxhighlight lang="perl">use Carp::Assert;
assert($a == 42);</syntaxhighlight>
 
There is also a number of ways to test assertions in test suites, for example:
<syntaxhighlight lang="perl">is $a, 42;
ok $a == 42;
cmp_ok $a, '==', 42, 'The answer should be 42';
Line 1,429 ⟶ 1,517:
User defined types allow the value to be automatically tested whenever it changes, and
can be disabled using the "without type_check" directive:
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #008080;">type</span> <span style="color: #000000;">int42</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">42</span>
Line 1,448 ⟶ 1,536:
 
You can also use constants to reduce code output on release versions:
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #008080;">global</span> <span style="color: #008080;">constant</span> <span style="color: #000000;">DEBUG</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- (or any other identifier name can be used)</span>
<span style="color: #008080;">global</span> <span style="color: #008080;">procedure</span> <span style="color: #000000;">check</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">flag</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">msg</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- see also assert() below</span>
Line 1,473 ⟶ 1,561:
first line terminates with a divide by zero, whereas the second and third produce a
slightly more user-friendly, and therefore potentially less developer-friendly message:
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">42</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">42</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"i is not 42!!"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
Line 1,484 ⟶ 1,572:
 
=={{header|PHP}}==
<syntaxhighlight lang="php"><?php
$a = 5
#...input or change $a here
Line 1,497 ⟶ 1,585:
 
The predicate/function that is tested but be "escaped" by <code>$</code> in order to not be evaluated before the test.
<syntaxhighlight lang=Picat"picat">go =>
 
%
Line 1,549 ⟶ 1,637:
The '[http://software-lab.de/doc/refA.html#assert assert]' function, in
combination with the tilde read macro, generates code only in debug mode:
<syntaxhighlight lang=PicoLisp"picolisp">...
~(assert (= N 42)) # Exists only in debug mode
...</syntaxhighlight>
Other possibilities are either to break into an error handler:
<syntaxhighlight lang=PicoLisp"picolisp">(let N 41
(unless (= N 42) (quit "Incorrect N" N)) ) # 'quit' throws an error
41 -- Incorrect N
?</syntaxhighlight>
or to stop at a debug break point, allowing to continue with the program:
<syntaxhighlight lang=PicoLisp"picolisp">(let N 41
(unless (= N 42) (! setq N 42)) ) # '!' is a breakpoint
(setq N 42) # Manually fix the value
Line 1,565 ⟶ 1,653:
 
=={{header|PL/I}}==
<syntaxhighlight lang="text">
/* PL/I does not have an assert function as such, */
/* but it is something that can be implemented in */
Line 1,589 ⟶ 1,677:
{{works with|SWI Prolog}}
 
<syntaxhighlight lang="prolog">
test(A):-
assertion(A==42).
Line 1,599 ⟶ 1,687:
The Macro below will only be included in the code if is compiled in debug mode, if so it will test the condition and if it fails it will inform with the message defined by the programmer, the line where it happened and in which source code file.
 
<syntaxhighlight lang=PureBasic"purebasic">Macro Assert(TEST,MSG="Assert: ")
CompilerIf #PB_Compiler_Debugger
If Not (TEST)
Line 1,609 ⟶ 1,697:
 
A implementation as defined above could be;
<syntaxhighlight lang=PureBasic"purebasic">A=42
Assert(A=42,"Assert that A=42")
A=42-1
Line 1,616 ⟶ 1,704:
 
=={{header|Python}}==
<syntaxhighlight lang="python">a = 5
#...input or change a here
assert a == 42 # throws an AssertionError when a is not 42
Line 1,625 ⟶ 1,713:
 
=={{header|QB64}}==
<syntaxhighlight lang="vb">$ASSERTS:CONSOLE
DO
Line 1,643 ⟶ 1,731:
 
=={{header|R}}==
<syntaxhighlight lang=R"r">stopifnot(a==42)</syntaxhighlight>
 
=={{header|Racket}}==
Line 1,649 ⟶ 1,737:
Racket has higher-order assertions known as ''contracts'' that can protect any values including functions and objects. Contracts are typically applied on the imports or exports of a module.
 
<syntaxhighlight lang=Racket"racket">#lang racket
 
(define/contract x
Line 1,666 ⟶ 1,754:
If typical assertion checking (i.e. error unless some boolean condition holds) is needed, that is also possible:
 
<syntaxhighlight lang=Racket"racket">#lang racket
 
(define x 80)
Line 1,675 ⟶ 1,763:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang=perl6"raku" line>my $a = (1..100).pick;
$a == 42 or die '$a ain\'t 42';</syntaxhighlight>
 
{{works with|pugs}}
''Note: This example uses an experimental feature, and does not work in the primary Perl 6 compiler, Rakudo.''
<syntaxhighlight lang=perl6># with a (non-hygienic) macro
macro assert ($x) { "$x or die 'assertion failed: $x'" }
assert('$a == 42');</syntaxhighlight>
 
=={{header|REXX}}==
===version 1===
<syntaxhighlight lang=REXX"rexx">/* REXX ***************************************************************
* There's no assert feature in Rexx. That's how I'd implement it
* 10.08.2012 Walter Pachl
Line 1,732 ⟶ 1,814:
<br>possible actions. &nbsp; Here, it just returns to the next REXX statement after the
'''call assert'''.
<syntaxhighlight lang="rexx">/*REXX program implements a simple ASSERT function; the expression can be compound. */
a = 1 /*assign a value to the A variable.*/
b = -2 /* " " " " " B " */
Line 1,758 ⟶ 1,840:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
x = 42
assert( x = 42 )
Line 1,767 ⟶ 1,849:
RLaB does not have a special function to deal with assertions. The following workaround will do the trick:
 
<syntaxhighlight lang=RLaB"rlab">
// test if 'a' is 42, and if not stop the execution of the code and print
// some error message
Line 1,775 ⟶ 1,857:
}
</syntaxhighlight>
 
=={{header|RPL}}==
There is no build-in assertion feature in RPL, but it can be easily programmed
≪ '''IF''' SWAP '''THEN''' ABORT '''ELSE''' DROP '''END''' ≫ ''''ASSRT'''' STO ''( condition message -- message )''
 
≪ 43 → a
≪ a 42 == "Not good" '''ASSRT'''
"This won't happen"
≫ ≫ EVAL
{{out}}
<pre>
1: "Not good"
</pre>
 
=={{header|Ruby}}==
This uses test/unit from the standard library.
 
<syntaxhighlight lang="ruby">require "test/unit/assertions"
include Test::Unit::Assertions
 
Line 1,795 ⟶ 1,890:
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
let x = 42;
assert!(x == 42);
Line 1,802 ⟶ 1,897:
 
=={{header|Sather}}==
<syntaxhighlight lang="sather">class MAIN is
main is
i ::= 41;
Line 1,814 ⟶ 1,909:
=={{header|Scala}}==
These two are the same thing, and are tagged <code>@elidable(ASSERTION)</code>:
<syntaxhighlight lang="scala">assert(a == 42)
assert(a == 42, "a isn't equal to 42")
assume(a == 42)
Line 1,821 ⟶ 1,916:
The next one does the same thing as above, but it is not tagged. Often used as a pre-condition
checker on class constructors.
<syntaxhighlight lang="scala">require(a == 42)
require(a == 42, "a isn't equal to 42")</syntaxhighlight>
 
This one checks a value and returns it for further use (here shown being printed). It
uses <code>assert</code>, which, as explained, gets tagged.
<syntaxhighlight lang="scala">println(a.ensuring(a == 42))
println(a.ensuring(a == 42, "a isn't equal to 42"))
println(a.ensuring(_ == 42))
Line 1,835 ⟶ 1,930:
 
{{trans|Common Lisp}}
<syntaxhighlight lang="scheme">(let ((x 42))
(assert (and (integer? x) (= x 42))))</syntaxhighlight>
 
=={{header|SETL}}==
<syntaxhighlight lang="ada">assert( n = 42 );</syntaxhighlight>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var num = pick(0..100);
assert_eq(num, 42); # dies when "num" is not 42</syntaxhighlight>
{{out}}
Line 1,850 ⟶ 1,945:
 
=={{header|Slate}}==
<syntaxhighlight lang="slate">load: 'src/lib/assert.slate'.
define: #n -> 7.
assert: n = 42 &description: 'That is not the Answer.'.</syntaxhighlight>
Line 1,856 ⟶ 1,951:
 
=={{header|Smalltalk}}==
<syntaxhighlight lang="smalltalk">foo := 41.
...
self assert: (foo == 42).</syntaxhighlight>
 
In TestCase and subclasses, a number of check methods are inherited; among them:
<syntaxhighlight lang="smalltalk">self assert: (... somethingMustEvaluateToTrue.. )
self should:[ some code ] raise: someException "ensures that an exception is raised</syntaxhighlight>
 
{{works with|Smalltalk/X}}
Object also implements assert:; these are evaluated dynamically, but can be disabled via a flag setting. Also the compiler can be instructed to ignore them for production code (which is not normally done; disabled instead by default):
<syntaxhighlight lang="smalltalk">self assert: (... somethingMustEvaluateToTrue.. ) "implemented in Object"</syntaxhighlight>
the implementation in Object raises an AssertionFailedError exception, which usually opens a debugger when in the IDE, but can be caught in deployed apps.
 
Line 1,874 ⟶ 1,969:
Assertions are analysed statically, before compilation or execution. They can appear in various places:
:inline in the code, either
<syntaxhighlight lang="ada">-# check X = 42;</syntaxhighlight>
::or
<syntaxhighlight lang="ada">-# assert X = 42;</syntaxhighlight>
:as a precondition on an operation:
<syntaxhighlight lang="ada">procedure P (X : in out Integer);
--# derives X from *;
--# pre X = 42;</syntaxhighlight>
:or as a postcondition on an operation:
<syntaxhighlight lang="ada">procedure P (X : in out Integer);
--# derives X from *;
--# post X = 42;</syntaxhighlight>
Example:
<syntaxhighlight lang="ada">X := 7;
--# check X = 42;</syntaxhighlight>
produces the following output:
Line 1,896 ⟶ 1,991:
=={{header|Standard ML}}==
Using exceptions:
<syntaxhighlight lang="sml">fun assert cond =
if cond then () else raise Fail "assert"
 
Line 1,906 ⟶ 2,001:
For instance, if a dataset contains two variables x, y, z, one can check if x<y for all data lines for which z>0, with:
 
<syntaxhighlight lang="stata">assert x<y if z>0</syntaxhighlight>
 
There is another command, '''[http://www.stata.com/help.cgi?confirm confirm]''', that can be used to check existence and type of program arguments or files. For instance, to check that the file titanium.dta exists:
 
<syntaxhighlight lang="stata">confirm file titanium.dta</syntaxhighlight>
 
If the file does not exist, an error is thrown with return code 601.
Line 1,916 ⟶ 2,011:
It's also possible to use '''[http://www.stata.com/help.cgi?error error]''' to throw an error if some condition is satisfied. However, this command can only print predefined error messages: it takes the error number as an argument. For instance:
 
<syntaxhighlight lang="stata">if (`n'==42) error 3
* Will print "no dataset in use"</syntaxhighlight>
 
To print a more sensible message, one would do instead:
 
<syntaxhighlight lang="stata">if (`n'==42) {
display as error "The correct answer is not 42."
exit 54
Line 1,929 ⟶ 2,024:
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">var a = 5
//...input or change a here
assert(a == 42) // aborts program when a is not 42
Line 1,939 ⟶ 2,034:
=={{header|Tcl}}==
{{tcllib|control}}
<syntaxhighlight lang="tcl">package require control
 
set x 5
Line 1,946 ⟶ 2,041:
<pre>assertion failed: $x == 42</pre>
 
{{omit from|gnuplot}}
{{omit from|NSIS}}
 
=={{header|UNIX Shell}}==
{{works with|bash}}
Assertions are not builtin commands, but we can add a function easily.
<syntaxhighlight lang="bash">assert() {
if test ! $1; then
[[ $2 ]] && echo "$2" >&2
Line 1,965 ⟶ 2,058:
 
=={{header|Vala}}==
<syntaxhighlight lang="vala">int a = 42;
int b = 33;
assert (a == 42);
Line 1,971 ⟶ 2,064:
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Sub test()
Dim a As Integer
a = 41
Line 1,981 ⟶ 2,074:
=={{header|VBScript}}==
====Definition====
<syntaxhighlight lang="vb">sub Assert( boolExpr, strOnFail )
if not boolExpr then
Err.Raise vbObjectError + 99999, , strOnFail
Line 1,988 ⟶ 2,081:
</syntaxhighlight>
====Invocation====
<syntaxhighlight lang="vb">dim i
i = 43
Assert i=42, "There's got to be more to life than this!"</syntaxhighlight>
====Output====
<syntaxhighlight lang=VBScript"vbscript">>cscript "C:\foo\assert.vbs"
C:\foo\assert.vbs(3, 3) (null): There's got to be more to life than this!</syntaxhighlight>
 
=={{header|Visual Basic}}==
VB's <code>Assert</code> only fires when run from within the IDE. When compiled, all <code>Debug</code> lines are ignored.
<syntaxhighlight lang="vb">Debug.Assert i = 42</syntaxhighlight>
 
=={{header|Visual Basic .NET}}==
See [[#C# and Visual Basic .NET]].
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="ecmascript">fn main(){
x := 43
assert x == 43 // Fine
assert x > 42 // Fine
assert x == 42 // Fails
}</syntaxhighlight>
 
{{out}}
<pre>
../rosetta/assert.v:5: FAIL: fn main.main: assert x == 42
left value: x = 43
right value: 42
V panic: Assertion failed...
v hash: e42dc8e
C:~/assert.12166200709334891880.tmp.c:6356: at _v_panic: Backtrace
C:~/assert.12166200709334891880.tmp.c:11581: by main__main
C:~/assert.12166200709334891880.tmp.c:11946: by wmain
0044d2a8 : by ???
0044d40b : by ???
7ffc4cd07034 : by ???
 
</pre>
 
=={{header|Wren}}==
Wren does not have assertions as such though we can write something similar.
<syntaxhighlight lang=ecmascript"wren">var assertEnabled = true
 
var assert = Fn.new { |cond|
Line 2,024 ⟶ 2,141:
[./assertion line 12] in (script)
</pre>
<br>
=={{header|Visual Basic .NET}}==
{{libheader|Wren-debug}}
See [[#C# and Visual Basic .NET]].
The above module also provides limited support for assertions.
<syntaxhighlight lang="wren">import "./debug" for Debug
 
var x = 42
=={{header|Vlang}}==
Debug.assert("x == 42", 4, x == 42) // fine
<syntaxhighlight lang=ecmascript>fn main(){
Debug.off
x := 43
Debug.assert("x > 42", assert6, x ==> 42) 43 // Fineno error
Debug.on
assert x > 42 // Fine
Debug.assert("x > 42", 8, x > 42) // error</syntaxhighlight>
assert x == 42 // Fails
}</syntaxhighlight>
 
{{out}}
<pre>
ASSERTION on line 8 labelled 'x > 42' failed. Aborting fiber.
../rosetta/assert.v:5: FAIL: fn main.main: assert x == 42
Assertion failure.
left value: x = 43
[./debug line 100] in assert(_,_,_)
right value: 42
[./assert line 8] in (script)
V panic: Assertion failed...
v hash: e42dc8e
C:~/assert.12166200709334891880.tmp.c:6356: at _v_panic: Backtrace
C:~/assert.12166200709334891880.tmp.c:11581: by main__main
C:~/assert.12166200709334891880.tmp.c:11946: by wmain
0044d2a8 : by ???
0044d40b : by ???
7ffc4cd07034 : by ???
 
</pre>
 
Line 2,055 ⟶ 2,165:
synthesized something like this.
 
<syntaxhighlight lang=XPL0"xpl0">proc Fatal(Str); \Display error message and terminate program
char Str;
[\return; uncomment this if "assertions" are to be disabled
Line 2,067 ⟶ 2,177:
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">sub assert(a)
if not a then
error "Assertion failed"
Line 2,076 ⟶ 2,186:
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">const assert = @import("std").debug.assert;
 
pub fn main() void {
const n: i64 = 43;
assert(1 == 0); // On failure, an `unreachable` is reached
assert(n == 42); // On failure, an `unreachable` is reached
}</syntaxhighlight>
 
Line 2,088 ⟶ 2,199:
There is no hardware support for error handling, but the programmer can do this the same way they would create any other <code>if</code> statement:
 
<syntaxhighlight lang="z80">ld a,(&C005) ;load A from memory (this is an arbitrary memory location designated as the home of our variable)
cp 42
jp nz,ErrorHandler</syntaxhighlight>
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">n:=42; (n==42) or throw(Exception.AssertionError);
n=41; (n==42) or throw(Exception.AssertionError("I wanted 42!"));</syntaxhighlight>
{{out}}
Line 2,105 ⟶ 2,216:
 
=={{header|zonnon}}==
<syntaxhighlight lang="zonnon">
module Assertions;
var
Line 2,114 ⟶ 2,225:
end Assertions.
</syntaxhighlight>
{{omit from|gnuplot}}
{{omit from|NSIS}}
162

edits