Assertions: Difference between revisions
m
syntax highlighting fixup automation
Puppydrum64 (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 13:
{{trans|Python}}
<
assert(a == 42)
assert(a == 42, ‘Error message’)</
=={{header|68000 Assembly}}==
<
BEQ continue
ILLEGAL ;causes an immediate jump to the illegal instruction vector.
continue:
; rest of program</
=={{header|Ada}}==
Using pragma Assert:
<
The behavior of pragma is controlled by pragma Assertion_Policy. Another way is to use the predefined package Ada.Assertions:
<
...
Assert (A = 42, "Oops!");</
The procedure Assert propagates Assertion_Error when condition is false.
Since Ada 2012 one may also specify preconditions and post-conditions for a subprogram.
<
(List : in Array_Type;
Value : in Integer;
Line 42:
Post =>
(if Found then Position in List'Range and then List (Position) = Value
else Position = List'Last);</
The precondition identified with "Pre =>" is an assertion that the length of the parameter List must be greater than zero. The post-condition identified with "Post =>" asserts that, upon completion of the procedure, if Found is true then Position is a valid index value in List and the value at the array element List(Position) equals the value of the Value parameter. If Found is False then Position is set to the highest valid index value for List.
=={{header|Aime}}==
<
x = 41;
if (x != 42) {
error("x is not 42");
}</
Executing the program will produce on standard error:
<pre>aime: assert: 5: x is not 42</pre>
Line 70:
In [[ELLA ALGOL 68]] the ASSERT is implemented as an operator in the ''environment'' prelude:
<
IF NOT valid
THEN type line on terminal(assertion);
terminal error( 661 {invalid assertion } )
FI;</
And can be "USEd" as follows:
<
USE standard,environment
BEGIN
Line 82:
"Oops!" ASSERT ( a = 42 )
END
FINISH</
=={{header|ALGOL W}}==
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.
<
integer a;
a := 43;
assert a = 42;
write( "this won't appear" )
end.</
=={{header|Apex}}==
Asserts that the specified condition is true. If it is not, a fatal error is returned that causes code execution to halt.
<
String myStr = 'test;
System.assert(myStr == 'something else', 'Assertion Failed Message');
</syntaxhighlight>
Asserts that the first two arguments are the same. If they are not, a fatal error is returned that causes code execution to halt.
<
Integer i = 5;
System.assertEquals(6, i, 'Expected 6, received ' + i);
</syntaxhighlight>
Asserts that the first two arguments are different. If they are the same, a fatal error is returned that causes code execution to halt.
<
Integer i = 5;
System.assertNotEquals(5, i, 'Expected different value than ' + i);
</syntaxhighlight>
'''You can’t catch an assertion failure using a try/catch block even though it is logged as an exception.'''
=={{header|Arturo}}==
<
ensure [a = 42]</
=={{header|AutoHotkey}}==
=== Exceptions ===
{{works with|AutoHotkey_L}}
<
Assert(a > 10)
Assert(a < 42) ; throws exception
Line 129:
If !bool
throw Exception("Expression false", -1)
}</
=== Legacy versions ===
<
{
OutputDebug, "a != 42" ; sends output to a debugger if connected
ListVars ; lists values of local and global variables
Pause ; pauses the script, use ExitApp to exit instead
}</
=={{header|AWK}}==
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".
<
BEGIN {
meaning = 6 * 7
Line 164:
}
}
</syntaxhighlight>
The above example produces the output below, and sets the program's exit code to 1 (the default is 0)
Line 172:
=={{header|Axe}}==
<
=={{header|BaCon}}==
<
answer = assertion(42)
PRINT "The ultimate answer is indeed ", answer
Line 198:
RETURN i
END FUNCTION</
{{out}}
Line 222:
=={{header|BASIC256}}==
{{works with|BASIC256|2.0.0.11}}
<
subroutine assert (condition, message)
if not condition then print "ASSERTION FAIED: ";message: throwerror 1
Line 229:
call assert(1+1=2, "but I don't expect this assertion to fail"): rem Does not throw an error
rem call assert(1+1=3, "and rightly so"): rem Throws an error
</syntaxhighlight>
=={{header|BBC BASIC}}==
<
END
DEF PROCassert(bool%)
IF NOT bool% THEN ERROR 100, "Assertion failed"
ENDPROC</
=={{header|BQN}}==
Line 255:
=={{header|Brat}}==
<
assert_equal 42 42
assert_equal 13 42 #Raises an exception</
=={{header|C}}==
<
int main(){
Line 269:
return 0;
}</
To turn off assertions, simply define the <tt>NDEBUG</tt> macro before where <tt><assert.h></tt> is included.
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:
<
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:
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.
<
static class Program
Line 309:
Console.WriteLine("After Debug.Assert");
}
}</
<
' Note: VB Visual Studio projects have System.Diagnostics imported by default,
' along with several other namespaces.
Line 331:
Console.WriteLine("After Debug.Assert")
End Sub
End Module</
{{out|note=for .NET Core debug builds when outside of a debugger}}
Line 357:
Subscribing an instance involves adding the following line to the beginning of Main() (with a semicolon in C#, of course ;)
<
=={{header|C++}}==
{{trans|C}}
<
int main()
Line 370:
assert(a == 42); // Aborts program if a is not 42, unless the NDEBUG macro was defined
// when including <cassert>, in which case it has no effect
}</
Note that assert does ''not'' get a <code>std::</code> prefix because it's a macro.
=={{header|Clojure}}==
<
(let [i 42]
(assert (= i 42)))
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(assert (and (integerp x) (= 42 x)) (x)))</
=={{header|Component Pascal}}==
Works with BlackBox Component Builder
<
MODULE Assertions;
VAR
Line 397:
Assertions.DoIt
</syntaxhighlight>
Output:
<pre>
Line 422:
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.
<
end
Line 429:
end
assert(12 == 42, "It appears that 12 doesn't equal 42")</
=={{header|D}}==
<
int foo(in bool condition) pure nothrow
Line 467:
// There are some different versions of this lazy function.
enforce(x == 42, "x is not 42");
}</
=={{header|Dart}}==
=== Assert ===
<
main() {
var i = 42;
assert( i == 42 );
}
</syntaxhighlight>
=== Expect ===
Testing assertions can be done using the test and expect functions in the test package
<
main() {
Line 493:
expect( j, equals(42) );
});
}</
=={{header|Delphi}}==
<
If an assertion fails, EAssertionFailed exception is raised.
Line 503:
The generation of assertion code can be disabled by compiler directive
<syntaxhighlight lang
Here is a simple console demo app which raises and handles assertion exception:
<
{$APPTYPE CONSOLE}
Line 527:
end;
Readln;
end.</
=={{header|DWScript}}==
Simple assertion, with a custom (optional) message
<
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
<
require
a = 42;
Line 540:
ensure
a = 42;
end;</
=={{header|Dyalect}}==
Dyalect has a built-in "assert" function:
<
assert(42, x)</
This function throws an exception if assertion fails.
Line 554:
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:
<
require(a == 42, "The Answer is Wrong.") # supplied message
require(a == 42, fn { `Off by ${a - 42}.` }) # computed only on failure</
=={{header|EchoLisp}}==
<
(assert (integer? 42)) → #t ;; success returns true
Line 571:
(assert (integer? 'quarante-deux) "☝️ expression must evaluate to the integer 42")
💥 error: ☝️ expression must evaluate to the integer 42 : assertion failed : (#integer? 'quarante-deux)
</syntaxhighlight>
=={{header|ECL}}==
<lang>
ASSERT(a = 42,'A is not 42!',FAIL);</
=={{header|Eiffel}}==
Line 584:
File called main.e:
<
creation main
feature main is
Line 595:
test.assert(io.last_integer);
end
end</
Another file called test.e:
<
feature assert(val: INTEGER) is
require
Line 604:
print("Thanks for the 42!%N");
end
end</
=={{header|Elixir}}==
<
defmodule AssertionTest do
Line 617:
assert 42 == return_5
end
end</
{{out}}
Line 639:
=={{header|Emacs Lisp}}==
<
(let ((x 41))
(cl-assert (= x 42) t "This shouldn't happen"))</
=={{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.
<
42
2> N = 43.
Line 654:
** exception error: no match of right hand side value 42
5> 42 = N.
42</
As such, the behavior of Erlang's assignment operator is extremely similar to a regular <tt>assert</tt> in other languages.
=={{header|Euphoria}}==
<
return i = 42
end type
Line 665:
fourty_two i
i = 41 -- type-check failure</
=={{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.
<
assert (x = 42)
test 43</
For additional information about assertions in .NET, see [[#C# and Visual Basic .NET]]
Line 679:
Throw an exception if the value on the top of the stack is not equal to 42:
<
42 assert=</
=={{header|FBSL}}==
Line 686:
This implementation evaluates the expression given to the function and displays a message if it evaluates to false.
<
DECLARE asserter
Line 699:
Assert("1>2")
PAUSE</
Output
<pre>Assertion: 1>2 failed
Line 706:
=={{header|Forth}}==
<
: assert a @ 42 <> throw ;
41 a ! assert</
=={{header|FreeBASIC}}==
<
' requires compilation with -g switch
Line 719:
'The rest of the code will not be executed
Print a
Sleep</
{{out}}
Line 727:
=={{header|GAP}}==
<
# GAP has assertions levels. An assertion is tested if its level
Line 745:
# Show current global level
AssertionLevel();
# 10</
=={{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—function name, file name, and line number.
<
func main() {
Line 756:
panic(42)
}
}</
Output:
<pre>
Line 773:
=={{header|Groovy}}==
<
assert it == 42 : "This: " + it + " is not the answer!"
}</
Test program:
<
checkTheAnswer(42)
println "before 'Hello Universe'..."
checkTheAnswer("Hello Universe")</
Output:
Line 791:
=={{header|Haskell}}==
<
main = let a = someValue in
assert (a == 42) -- throws AssertionFailed when a is not 42
somethingElse -- what to return when a is 42</
=={{header|Icon}} and {{header|Unicon}}==
<
runerr(n,( expression ,"Assertion/error - message.")) # Throw (and possibly trap) an error number n if expression succeeds.
...
stop(( expression ,"Assertion/stop - message.")) # Terminate program if expression succeeds.
...</
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:
<
$define DEBUG 1 # this allows the assertions to go through
Line 820:
check (12)
end
</syntaxhighlight>
This produces the output:
Line 831:
=={{header|J}}==
<
=={{header|Java}}==
<
public static void main(String[] args) {
Line 849:
// The error message can be any non-void expression.
}
}</
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.
=={{header|JavaScript}}==
<
function check() {
try {
Line 878:
answer = 23;
check();
</syntaxhighlight>
{{out}}<pre>
Line 936:
'''assert.jq'''
<
def m: $msg | if type == "string" then . else [.[]] | join(":") end;
if env.JQ_ASSERT then
Line 955:
end
else . end;
</syntaxhighlight>
'''Example'''
<syntaxhighlight lang=jq>
# File: example.jq
# This example assumes the availability of the $__loc__ function
Line 970:
asserteq($x; 42; $__loc__);
test</
'''Invocation'''
JQ_ASSERT=1 jq -n -f example.jq
Line 984:
=={{header|Julia}}==
<
# @assert macro checks the supplied conditional expression, with the expression
Line 995:
x::String
# ERROR: LoadError: TypeError: in typeassert, expected String, got Int64
</syntaxhighlight>
=={{header|Kotlin}}==
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.
<
val a = 42
assert(a == 43)
}</
{{out}}
Line 1,013:
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
<
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,020:
check(fullName.contains(" ")) { "fullname was expected to have a space...?" } // IllegalStateException
return fullName
}</
=={{header|Lasso}}==
<
fail_if(
#a != 42,
error_code_runtimeAssertion,
error_msg_runtimeAssertion + ": #a is not 42"
)</
{{out}}
<pre>-9945 Runtime assertion: #a is not 42</pre>
Line 1,036:
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,051:
end if
end sub
</syntaxhighlight>
{{out}}
Line 1,066:
=={{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:
<
on assert (ok, message)
if not ok then
Line 1,082:
assert(x=42, "Assertion 'x=42' failed")
put "this will never show up"
end</
=={{header|Lisaac}}==
<
=={{header|Lua}}==
<
assert (a == 42)
assert (a == 42,'\''..a..'\' is not the answer to life, the universe, and everything')</
=={{header|M2000 Interpreter}}==
Line 1,098:
<
Module Assert {
\\ This is a global object named Rec
Line 1,159:
}
Assert
</syntaxhighlight>
=={{header|Maple}}==
(Taken from Lua, above.)
<
ASSERT( a = 42 );
ASSERT( a = 42, "a is not the answer to life, the universe, and everything" );</
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
=={{header|MATLAB}} / {{header|Octave}}==
<
Sample Output:
<
assert(x == 42,'Assertion Failed: x = %d, not 42.',x);
??? Assertion Failed: x = 3, not 42.
</syntaxhighlight>
=={{header|Metafont}}==
Line 1,185:
Metafont has no really an assert built in, but it can easily created:
<
This <code>assert</code> macro uses the <code>errmessage</code> built in to show the "error". The
Line 1,192:
Usage example:
<
assert(n=42);
message "ok";</
Output (failed assertion):
Line 1,209:
=={{header|Modula-3}}==
<code>ASSERT</code> is a pragma, that creates a run-time error if it returns <code>FALSE</code>.
<
Assertions can be ignored in the compiler by using the <code>-a</code> switch.
=={{header|Nanoquery}}==
<
assert (a = 42)</
=={{header|Nemerle}}==
A basic assertion uses the <tt>assert</tt> keyword:
<
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:
<
class SampleClass
Line 1,235:
ensures value.Length > 0 // ensures keyword indicates postcondition
{ ... } // value is a special symbol that indicates the method's return value
}</
The design by contract macros throw <tt>Nemerle.AssertionException</tt>'s unless another Exception is specified using the <tt>otherwise</tt> keyword after the <tt>requires/ensures</tt> statement.
For further details on design by contract macros, see [http://nemerle.org/wiki/index.php?title=Design_by_contract_macros here].
Line 1,248:
* it is a pattern, numbers match themselves exactly, other patterns that would match: <tt>Int</tt>, <tt>0..100</tt>, <tt>Any</tt>
<
assert(a==42)
assert(a, 42)
assert(a==42, "Not 42!")
assert(a, 42, "Not 42!")</
=={{header|Nim}}==
In Nim there are two main ways to check assertions.
<
assert(a == 42, "Not 42!")</
This first kind of assertion may be disabled by compiling with --assertions:off or -d:danger.
<
doAssert(a == 42, "Not 42!")</
This second kind of assertion cannot be disabled.
=={{header|Oberon-2}}==
Oxford Oberon-2
<
MODULE Assertions;
VAR
Line 1,274:
ASSERT(a = 42);
END Assertions.
</syntaxhighlight>
Output:
<pre>
Line 1,284:
=={{header|Objeck}}==
If variable is not equal to 42 a stack trace is generated and the program is halts.
<
function : Main(args : String[]) ~ Nil {
if(args->Size() = 1) {
Line 1,292:
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
For use within an Objective-C method:
<
If you want to use formatting arguments, you need to use the assertion macro corresponding to your number of formatting arguments:
<
Within a regular C function you should use <code>NSCAssert</code> or <code>NSCAssert''N''</code> instead.
Line 1,306:
=={{header|OCaml}}==
<
assert (a = 42); (* throws Assert_failure when a is not 42 *)
(* evaluate stuff to return here when a is 42 *)</
It is possible to compile with the parameter <code>-noassert</code> then the compiler won't compile the assertion checks.
Line 1,320:
If an assertion is ko (and if oforth is launched using --a), an exception is raised.
<
assert: [ n isInteger ]
assert: [ n 42 == ]
System.Out "Assertions are ok, parameters are : " << n << ", " << m << cr ;</
{{out}}
Line 1,336:
=={{header|Ol}}==
<
(define i 24)
(assert i ===> 42)
</syntaxhighlight>
{{Out}}
<pre>
Line 1,356:
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).
<
proc {PrintNumber N}
N=42 %% assert
Line 1,363:
in
{PrintNumber 42} %% ok
{PrintNumber 11} %% throws </
Output:
Line 1,378:
PARI can use any of the usual C methods for making assertions. GP has no built-in assertions.
{{trans|C}}
<
#include <pari/pari.h>
Line 1,388:
assert(equalis(a, 42)); /* Aborts program if a is not 42, unless the NDEBUG macro was defined */
}</
More common is the use of <code>pari_err_BUG</code> in such cases:
<
=={{header|Pascal}}==
Line 1,399:
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.
<
chomp(my $a = <>);
Line 1,407:
die "Error message\n" unless $a == 42;
die "Error message\n" if not $a == 42;
die "Error message\n" if $a != 42;</
This idiom is typically used during file operations:
<
or die "Cannot open file: $!\n"; # $! contains the error message from the last error</
It is not needed whith the "autodie" pragma:
<
open my $fh, '<', 'file'; # automatically throws an exception on failure</
Some third-party modules provide other ways of using assertions in Perl:
<
assert($a == 42);</
There is also a number of ways to test assertions in test suites, for example:
<
ok $a == 42;
cmp_ok $a, '==', 42, 'The answer should be 42';
# etc.</
=={{header|Phix}}==
User defined types allow the value to be automatically tested whenever it changes, and
can be disabled using the "without type_check" directive:
<!--<
<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,437:
<span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">41</span> <span style="color: #000080;font-style:italic;">-- type-check failure (desktop/Phix only)</span>
<!--</
When a type check occurs, program execution halts and if the program was run from the
editor, it automatically jumps to the offending source file and line.
Line 1,448:
You can also use constants to reduce code output on release versions:
<!--<
<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,462:
<span style="color: #000000;">check</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">42</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"i is not 42!!"</span><span style="color: #0000FF;">)</span>
<!--</
Note that while the body of check() and the call to it are suppressed, the calculation
of the expression (i=42) may still generate code; sometimes further improvements to the
Line 1,473:
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:
<!--<
<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>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">42</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"i is not 42!!"</span><span style="color: #0000FF;">)</span>
<!--</
The assert statment is really just shorthand for the crash statement above it, except that
the error message is optional (defaults to "assertion failure").
Line 1,484:
=={{header|PHP}}==
<
$a = 5
#...input or change $a here
assert($a == 42) # when $a is not 42, take appropriate actions,
# which is set by assert_options()
?></
=={{header|Picat}}==
Line 1,497:
The predicate/function that is tested but be "escaped" by <code>$</code> in order to not be evaluated before the test.
<
%
Line 1,533:
println(Name ++ ": " ++ cond(apply(A) == Expected, "ok", "not ok")).
assert_failure(Name, A, Expected) =>
println(Name ++ ": " ++ cond(apply(A) != Expected , "ok", "not ok")).</
{{out}}
Line 1,549:
The '[http://software-lab.de/doc/refA.html#assert assert]' function, in
combination with the tilde read macro, generates code only in debug mode:
<
~(assert (= N 42)) # Exists only in debug mode
...</
Other possibilities are either to break into an error handler:
<
(unless (= N 42) (quit "Incorrect N" N)) ) # 'quit' throws an error
41 -- Incorrect N
?</
or to stop at a debug break point, allowing to continue with the program:
<
(unless (= N 42) (! setq N 42)) ) # '!' is a breakpoint
(setq N 42) # Manually fix the value
! # Hit ENTER to leave the breakpoint
-> 42</
=={{header|PL/I}}==
Line 1,584:
assert(a, 42);
</syntaxhighlight>
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<
test(A):-
assertion(A==42).
</syntaxhighlight>
=={{header|PureBasic}}==
Line 1,599:
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.
<
CompilerIf #PB_Compiler_Debugger
If Not (TEST)
Line 1,606:
EndIf
CompilerEndIf
EndMacro</
A implementation as defined above could be;
<
Assert(A=42,"Assert that A=42")
A=42-1
Assert(A=42)</
Where the second test would fail resulting in a message to the programmer with cause (if given by programmer), code line & file.
=={{header|Python}}==
<
#...input or change a here
assert a == 42 # throws an AssertionError when a is not 42
assert a == 42, "Error message" # throws an AssertionError
# when a is not 42 with "Error message" for the message
# the error message can be any expression</
It is possible to turn off assertions by running Python with the <tt>-O</tt> (optimizations) flag.
=={{header|QB64}}==
<
DO
Line 1,640:
IF value > 1 THEN plural$ = "s"
myFunc$ = STRING$(value, "*") + STR$(value) + " star" + plural$ + " :-)"
END FUNCTION</
=={{header|R}}==
<
=={{header|Racket}}==
Line 1,649:
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.
<
(define/contract x
Line 1,662:
(f 42) ; succeeds
(f "foo") ; contract error!
</syntaxhighlight>
If typical assertion checking (i.e. error unless some boolean condition holds) is needed, that is also possible:
<
(define x 80)
(unless (= x 42)
(error "a is not 42")) ; will error
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<
$a == 42 or die '$a ain\'t 42';</
{{works with|pugs}}
''Note: This example uses an experimental feature, and does not work in the primary Perl 6 compiler, Rakudo.''
<
macro assert ($x) { "$x or die 'assertion failed: $x'" }
assert('$a == 42');</
=={{header|REXX}}==
===version 1===
<
* There's no assert feature in Rexx. That's how I'd implement it
* 10.08.2012 Walter Pachl
Line 1,709:
End
Return
Syntax: Say 'program terminated'</
Output:
<pre>
Line 1,732:
<br>possible actions. Here, it just returns to the next REXX statement after the
'''call assert'''.
<
a = 1 /*assign a value to the A variable.*/
b = -2 /* " " " " " B " */
Line 1,746:
assert: if arg(1)=1 then return; parse value sourceline(sigl) with x; say
say '===== ASSERT failure in REXX line' sigl", the statement is:"; say '=====' x
say; return</
{{out|output|text= when using the internal defaults:}}
<pre>
Line 1,758:
=={{header|Ring}}==
<
x = 42
assert( x = 42 )
assert( x = 100 )
</syntaxhighlight>
=={{header|RLaB}}==
RLaB does not have a special function to deal with assertions. The following workaround will do the trick:
<
// test if 'a' is 42, and if not stop the execution of the code and print
// some error message
Line 1,774:
stop("a is not 42 as expected, therefore I stop until this issue is resolved!");
}
</syntaxhighlight>
=={{header|Ruby}}==
This uses test/unit from the standard library.
<
include Test::Unit::Assertions
Line 1,789:
# Ruby 1.9: e is a MiniTest::Assertion
puts e
end</
Output: <pre><42> expected but was
Line 1,795:
=={{header|Rust}}==
<
let x = 42;
assert!(x == 42);
assert_eq!(x, 42);
</syntaxhighlight>
=={{header|Sather}}==
<
main is
i ::= 41;
Line 1,808:
-- ...
end;
end;</
(The current GNU Sather compiler v1.2.3 I am using to test the code seems to ignore the assertion and no fatal error is raised, despite Sather should, see e.g. [http://www.gnu.org/software/sather/docs-1.2/tutorial/safety2208.html here]).
Line 1,814:
=={{header|Scala}}==
These two are the same thing, and are tagged <code>@elidable(ASSERTION)</code>:
<
assert(a == 42, "a isn't equal to 42")
assume(a == 42)
assume(a == 42, "a isn't equal to 42")</
The next one does the same thing as above, but it is not tagged. Often used as a pre-condition
checker on class constructors.
<
require(a == 42, "a isn't equal to 42")</
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.
<
println(a.ensuring(a == 42, "a isn't equal to 42"))
println(a.ensuring(_ == 42))
println(a.ensuring(_ == 42, "a isn't equal to 42"))</
=={{header|Scheme}}==
Line 1,835:
{{trans|Common Lisp}}
<
(assert (and (integer? x) (= x 42))))</
=={{header|SETL}}==
<
=={{header|Sidef}}==
<
assert_eq(num, 42); # dies when "num" is not 42</
{{out}}
<pre>
Line 1,850:
=={{header|Slate}}==
<
define: #n -> 7.
assert: n = 42 &description: 'That is not the Answer.'.</
raises an <tt>AssertionFailed</tt> condition (an <tt>Error</tt>).
=={{header|Smalltalk}}==
<
...
self assert: (foo == 42).</
In TestCase and subclasses, a number of check methods are inherited; among them:
<
self should:[ some code ] raise: someException "ensures that an exception is raised</
{{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):
<
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:
Assertions are analysed statically, before compilation or execution. They can appear in various places:
:inline in the code, either
<
::or
<
:as a precondition on an operation:
<
--# derives X from *;
--# pre X = 42;</
:or as a postcondition on an operation:
<
--# derives X from *;
--# post X = 42;</
Example:
<
--# check X = 42;</
produces the following output:
<pre>H1: true .
Line 1,896:
=={{header|Standard ML}}==
Using exceptions:
<
if cond then () else raise Fail "assert"
val () = assert (x = 42)</
=={{header|Stata}}==
Line 1,906:
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:
<
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
If the file does not exist, an error is thrown with return code 601.
Line 1,916:
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:
<
* Will print "no dataset in use"</
To print a more sensible message, one would do instead:
<
display as error "The correct answer is not 42."
exit 54
}</
Then, if '''[http://www.stata.com/help.cgi?capture capture]''' is used to trap the error, the return code (here 54) can be retrieved in '''[http://www.stata.com/help.cgi?_variables _rc]'''.
=={{header|Swift}}==
<
//...input or change a here
assert(a == 42) // aborts program when a is not 42
assert(a == 42, "Error message") // aborts program
// when a is not 42 with "Error message" for the message
// the error message must be a static string</
In release mode assertion checks are turned off.
=={{header|Tcl}}==
{{tcllib|control}}
<
set x 5
control::assert {$x == 42}</
Produces the output:
<pre>assertion failed: $x == 42</pre>
Line 1,952:
{{works with|bash}}
Assertions are not builtin commands, but we can add a function easily.
<
if test ! $1; then
[[ $2 ]] && echo "$2" >&2
Line 1,962:
((x--))
assert "$x -eq 42" "that's not the answer"
echo "won't get here"</
=={{header|Vala}}==
<
int b = 33;
assert (a == 42);
assert (b == 42); // will break the program with "assertion failed" error</
=={{header|VBA}}==
<
Dim a As Integer
a = 41
Debug.Assert a = 42
End Sub</
{{out}}
When run in the development area executing halts and highlights with yellow background the debug.assert line.
Line 1,981:
=={{header|VBScript}}==
====Definition====
<
if not boolExpr then
Err.Raise vbObjectError + 99999, , strOnFail
end if
end sub
</syntaxhighlight>
====Invocation====
<
i = 43
Assert i=42, "There's got to be more to life than this!"</
====Output====
<
C:\foo\assert.vbs(3, 3) (null): There's got to be more to life than this!</
=={{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.
<
=={{header|Visual Basic .NET}}==
Line 2,004:
=={{header|Wren}}==
Wren does not have assertions as such though we can write something similar.
<
var assert = Fn.new { |cond|
Line 2,015:
assert.call(x > 42) // no error
assertEnabled = true
assert.call(x > 42) // error</
{{out}}
Line 2,028:
=={{header|Vlang}}==
<
x := 43
assert x == 43 // Fine
assert x > 42 // Fine
assert x == 42 // Fails
}</
{{out}}
Line 2,055:
synthesized something like this.
<
char Str;
[\return; uncomment this if "assertions" are to be disabled
Line 2,064:
];
if X#42 then Fatal("X#42");</
=={{header|Yabasic}}==
<
if not a then
error "Assertion failed"
Line 2,073:
end sub
assert(myVar = 42)</
=={{header|Zig}}==
<
pub fn main() void {
assert(1 == 0); // On failure, an `unreachable` is reached
}</
Zig's assert gives a stack trace for debugging on failure.
Line 2,088:
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:
<
cp 42
jp nz,ErrorHandler</
=={{header|zkl}}==
<
n=41; (n==42) or throw(Exception.AssertionError("I wanted 42!"));</
{{out}}
<pre>
Line 2,105:
=={{header|zonnon}}==
<
module Assertions;
var
Line 2,113:
assert(a = 42,100)
end Assertions.
</syntaxhighlight>
|