Assertions: Difference between revisions
→{{header|Ruby}}: Make this work with Ruby 1.9. Also just print the exception message, instead of making own message. |
PascalABC.NET |
||
(182 intermediate revisions by more than 100 users not shown) | |||
Line 1: | Line 1: | ||
{{task|Basic language learning}} |
|||
{{task|Basic language learning}}Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw [[exceptions]] and some treat it as a break point. |
|||
Assertions are a way of breaking out of code when there is an error or an unexpected input. |
|||
Show an assertion in your language by asserting that an integer variable is equal to 42. |
|||
Some languages throw [[exceptions]] and some treat it as a break point. |
|||
;Task: |
|||
Show an assertion in your language by asserting that an integer variable is equal to '''42'''. |
|||
<br><br> |
|||
=={{header|11l}}== |
|||
{{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. |
|||
continue: |
|||
; rest of program</syntaxhighlight> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
Using pragma Assert: |
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: |
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!");</ |
Assert (A = 42, "Oops!");</syntaxhighlight> |
||
The procedure Assert propagates Assertion_Error when condition is false. |
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; |
|||
Found : out Boolean; |
|||
Position : out Positive) with |
|||
Depends => ((Found, Position) => (List, Value)), |
|||
Pre => (List'Length > 0), |
|||
Post => |
|||
(if Found then Position in List'Range and then List (Position) = Value |
|||
else Position = List'Last);</syntaxhighlight> |
|||
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}}== |
|||
<syntaxhighlight lang="aime">integer x; |
|||
x = 41; |
|||
if (x != 42) { |
|||
error("x is not 42"); |
|||
}</syntaxhighlight> |
|||
Executing the program will produce on standard error: |
|||
<pre>aime: assert: 5: x is not 42</pre> |
|||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 27: | Line 70: | ||
In [[ELLA ALGOL 68]] the ASSERT is implemented as an operator in the ''environment'' prelude: |
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 |
IF NOT valid |
||
THEN type line on terminal(assertion); |
THEN type line on terminal(assertion); |
||
terminal error( 661 {invalid assertion } ) |
terminal error( 661 {invalid assertion } ) |
||
FI;</ |
FI;</syntaxhighlight> |
||
And can be "USEd" as follows: |
And can be "USEd" as follows: |
||
< |
<syntaxhighlight lang="algol68">PROGRAM assertions CONTEXT VOID |
||
USE standard,environment |
USE standard,environment |
||
BEGIN |
BEGIN |
||
Line 39: | Line 82: | ||
"Oops!" ASSERT ( a = 42 ) |
"Oops!" ASSERT ( a = 42 ) |
||
END |
END |
||
FINISH</ |
FINISH</syntaxhighlight> |
||
=={{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. |
|||
<syntaxhighlight lang="algolw">begin |
|||
integer a; |
|||
a := 43; |
|||
assert a = 42; |
|||
write( "this won't appear" ) |
|||
end.</syntaxhighlight> |
|||
=={{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'); |
|||
</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. |
|||
<syntaxhighlight lang="apex"> |
|||
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. |
|||
<syntaxhighlight lang="apex"> |
|||
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}}== |
|||
<syntaxhighlight lang="rebol">a: 42 |
|||
ensure [a = 42]</syntaxhighlight> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
=== Exceptions === |
|||
<lang AutoHotkey>if (a != 42) |
|||
{{works with|AutoHotkey_L}} |
|||
<syntaxhighlight lang="ahk">a := 42 |
|||
Assert(a > 10) |
|||
Assert(a < 42) ; throws exception |
|||
Assert(bool){ |
|||
If !bool |
|||
throw Exception("Expression false", -1) |
|||
}</syntaxhighlight> |
|||
=== Legacy versions === |
|||
<syntaxhighlight lang="autohotkey">if (a != 42) |
|||
{ |
{ |
||
OutputDebug, "a != 42" ; sends output to a debugger if connected |
OutputDebug, "a != 42" ; sends output to a debugger if connected |
||
ListVars ; lists values of local and global variables |
ListVars ; lists values of local and global variables |
||
Pause ; pauses the script, use ExitApp to exit instead |
Pause ; pauses the script, use ExitApp to exit instead |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AWK}}== |
|||
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 |
|||
assert(meaning == 42, "Integer mathematics failed") |
|||
assert(meaning == 42) |
|||
meaning = strtonum("42 also known as forty-two") |
|||
assert(meaning == 42, "Built-in function failed") |
|||
meaning = "42" |
|||
assert(meaning == 42, "Dynamic type conversion failed") |
|||
meaning = 6 * 9 |
|||
assert(meaning == 42, "Ford Prefect's experiment failed") |
|||
print "That's all folks" |
|||
exit |
|||
} |
|||
# Errormsg is optional, displayed if assertion fails |
|||
function assert(cond, errormsg){ |
|||
if (!cond) { |
|||
if (errormsg != "") print errormsg |
|||
exit 1 |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
The above example produces the output below, and sets the program's exit code to 1 (the default is 0) |
|||
<pre> |
|||
Ford Prefect's experiment failed |
|||
</pre> |
|||
=={{header|Axe}}== |
|||
<syntaxhighlight lang="axe">A=42??Returnʳ</syntaxhighlight> |
|||
=={{header|BASIC}}== |
|||
==={{header|BaCon}}=== |
|||
<syntaxhighlight lang="qbasic">' Assertions |
|||
answer = assertion(42) |
|||
PRINT "The ultimate answer is indeed ", answer |
|||
PRINT "Now, expect a failure, unless NDEBUG defined at compile time" |
|||
answer = assertion(41) |
|||
PRINT answer |
|||
END |
|||
' Ensure the given number is the ultimate answer |
|||
FUNCTION assertion(NUMBER i) |
|||
' BaCon can easily be intimately integrated with C |
|||
USEH |
|||
#include <assert.h> |
|||
END USEH |
|||
' If the given expression is not true, abort the program |
|||
USEC |
|||
assert(i == 42); |
|||
END USEC |
|||
RETURN i |
|||
END FUNCTION</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ bacon -q assertion.bac && ./assertion |
|||
Converting 'assertion.bac'... done, 24 lines were processed in 0.006 seconds. |
|||
Compiling 'assertion.bac'... cc -c assertion.bac.c |
|||
cc -o assertion assertion.bac.o -lbacon -lm |
|||
Done, program 'assertion' ready. |
|||
The ultimate answer is indeed 42 |
|||
Now, expect a failure, unless NDEBUG defined at compile time |
|||
assertion: assertion.assertion.h:16: assertion: Assertion `i == 42' failed. |
|||
ERROR: signal ABORT received - internal error. Try to compile the program with TRAP LOCAL to find the cause. |
|||
prompt$ bacon -q -o '-DNDEBUG' assertion.bac && ./assertion |
|||
Converting 'assertion.bac'... done, 24 lines were processed in 0.003 seconds. |
|||
Compiling 'assertion.bac'... cc -DNDEBUG -c assertion.bac.c |
|||
cc -o assertion assertion.bac.o -lbacon -lm |
|||
Done, program 'assertion' ready. |
|||
The ultimate answer is indeed 42 |
|||
Now, expect a failure, unless NDEBUG defined at compile time |
|||
41</pre> |
|||
==={{header|BASIC256}}=== |
|||
{{works with|BASIC256|2.0.0.11}} |
|||
<syntaxhighlight lang="basic256"> |
|||
subroutine assert (condition, message) |
|||
if not condition then print "ASSERTION FAIED: ";message: throwerror 1 |
|||
end subroutine |
|||
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}}=== |
|||
<syntaxhighlight lang="bbcbasic"> PROCassert(a% = 42) |
|||
END |
|||
DEF PROCassert(bool%) |
|||
IF NOT bool% THEN ERROR 100, "Assertion failed" |
|||
ENDPROC</syntaxhighlight> |
|||
=={{header|BQN}}== |
|||
BQN has a primitive for logical assertions called Assert(<code>!</code>). |
|||
Called with a single argument, it throws an error if its argument is not 1. |
|||
Called with a left argument, it prints the left argument, and then throws an error. |
|||
<pre> ! 2=3 # Failed |
|||
Error: Assertion error |
|||
at ! 2=3 # Failed |
|||
^ |
|||
"hello" ! 2=3 # Failed |
|||
Error: hello |
|||
at "hello" ! 2=3 # Failed</pre> |
|||
=={{header|Brat}}== |
|||
<syntaxhighlight lang="brat">squish import :assert :assertions |
|||
assert_equal 42 42 |
|||
assert_equal 13 42 #Raises an exception</syntaxhighlight> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <assert.h> |
||
int main(){ |
int main(){ |
||
Line 57: | Line 270: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
To turn off assertions, simply define the <tt>NDEBUG</tt> macro before where <tt><assert.h></tt> is included. |
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: |
|||
<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. |
|||
<!--Putting the languages together for once to avoid duplicating the passage.--> |
|||
=={{header|C sharp|C#}} and {{header|Visual Basic .NET}}== |
|||
.NET provides the Debug.Assert and Trace.Assert methods, which notify TraceListener instances subscribed to the program's trace output if the specified condition is false. Both methods also have overloads that allow a specified string to be added to the default message of the assertion, which consists of "Assertion Failed" and a stack trace for the location of the assertion. |
|||
The behavior of a failed assertion is controlled by the listeners in the TraceListeners collection shared by the Debug and Trace classes. By default, the collection contains an instance of the DefaultTraceListener class, which uses functions in the Windows API that notify attached debuggers, if any. Additional behavior depends on the framework version that the application is running in: |
|||
* In .NET Core applications, if no debuggers are attached, failed Debug.Assert assertions for non-UI applications terminate the program and write the assertion message to the console, while failed Trace.Assert assertions do not affect execution. In this respect, a failed Debug assertion behaves similarly to an exception. |
|||
* In .NET Framework applications, for both types of assertions, a special instance of the Abort-Retry-Ignore message box containing the assertion message is displayed (even with a debugger attached). "Abort" terminates the program; "Retry" switches to the location of the assertion in source code if the application is running in a debugger, or, if none are attached, prompts to launch a just-in-time debugger; and "Ignore" continues execution past the assertion. |
|||
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 |
|||
{ |
|||
static void Main() |
|||
{ |
|||
int a = 0; |
|||
Console.WriteLine("Before"); |
|||
// Always hit. |
|||
Trace.Assert(a == 42, "Trace assertion failed"); |
|||
Console.WriteLine("After Trace.Assert"); |
|||
// Only hit in debug builds. |
|||
Debug.Assert(a == 42, "Debug assertion failed"); |
|||
Console.WriteLine("After Debug.Assert"); |
|||
} |
|||
}</syntaxhighlight> |
|||
<syntaxhighlight lang="vbnet">Imports System.Diagnostics |
|||
' Note: VB Visual Studio projects have System.Diagnostics imported by default, |
|||
' along with several other namespaces. |
|||
Module Program |
|||
Sub Main() |
|||
Dim a As Integer = 0 |
|||
Console.WriteLine("Before") |
|||
' Always hit. |
|||
Trace.Assert(a = 42, "Trace assertion failed: The Answer was incorrect") |
|||
Console.WriteLine("After Trace.Assert") |
|||
' Only hit in debug builds. |
|||
Debug.Assert(a = 42, "Debug assertion failed: The Answer was incorrect") |
|||
Console.WriteLine("After Debug.Assert") |
|||
End Sub |
|||
End Module</syntaxhighlight> |
|||
{{out|note=for .NET Core debug builds when outside of a debugger}} |
|||
<pre>Before |
|||
After Trace.Assert |
|||
Assertion Failed |
|||
Debug assertion failed |
|||
at Program.Main() in FILENAME:line 21</pre> |
|||
{{out}} |
|||
In .NET Core applications, this is the output |
|||
* when a debugger is attached and is used to continue past both assertions when they fail, or |
|||
* in release builds of the program, where the call to Debug.Assert is removed and the Trace.Assert assertion is hit but has no visible effects. |
|||
In .NET Framework applications, assertions never show up in the console and so the output is this when a debugger or the "Ignore" option used to continue past the assertions. |
|||
<pre>Before |
|||
After Trace.Assert |
|||
After Debug.Assert</pre> |
|||
'''Displaying Trace assertions in console:''' |
|||
To "see" the Trace.Assert assertion, additional TraceListener instances must be subscribed by the program. In the .NET Framework, there are several built-in subclasses of TraceListener, including ConsoleTraceListener, which writes trace messages to the console. In .NET Core, these classes are available starting from .NET Core 3.0. |
|||
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++}}== |
=={{header|C++}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="cpp">#include <cassert> // assert.h also works |
||
int main() |
int main() |
||
Line 71: | Line 371: | ||
assert(a == 42); // Aborts program if a is not 42, unless the NDEBUG macro was defined |
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 |
// when including <cassert>, in which case it has no effect |
||
}</ |
}</syntaxhighlight> |
||
Note that assert does ''not'' get a <code>std::</code> prefix because it's a macro. |
Note that assert does ''not'' get a <code>std::</code> prefix because it's a macro. |
||
=={{header|C sharp|C#}}== |
|||
<lang csharp>using System.Diagnostics; |
|||
Debug.Assert(a == 42);</lang> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
<syntaxhighlight lang="clojure"> |
|||
<lang Clojure> |
|||
(let [i 42] |
(let [i 42] |
||
(assert (= i 42))) |
(assert (= i 42))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{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 |
|||
x: INTEGER; |
|||
PROCEDURE DoIt*; |
|||
BEGIN |
|||
x := 41; |
|||
ASSERT(x = 42); |
|||
END DoIt; |
|||
END Assertions. |
|||
Assertions.DoIt |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
TRAP 0 |
|||
Assertions.DoIt [0000001DH] |
|||
Kernel.Call [00001A7CH] |
|||
.adr INTEGER 1685454913 |
|||
.kind INTEGER 0 |
|||
.n INTEGER 0 |
|||
.p INTEGER 0 |
|||
.par ARRAY 256 OF INTEGER elements |
|||
.r REAL 8.70603013185328E+175 |
|||
.sig POINTER [64760018H] |
|||
.size INTEGER 2287288 |
|||
.sp INTEGER 256 |
|||
.typ POINTER NIL |
|||
Meta.Item.ParamCallVal [00002B5EH] |
|||
.adr INTEGER 1685454913 |
|||
.data ARRAY 256 OF INTEGER elements |
|||
</pre> |
|||
=={{header|Crystal}}== |
|||
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 |
|||
def assert(predicate : Bool, msg = "The asserted condition was false") |
|||
raise AssertionError.new(msg) unless predicate |
|||
end |
|||
assert(12 == 42, "It appears that 12 doesn't equal 42")</syntaxhighlight> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
<syntaxhighlight lang="d">import std.exception: enforce; |
|||
int foo(in bool condition) pure nothrow |
|||
in { |
|||
// Assertions are used in contract programming. |
|||
assert(condition); |
|||
} out(result) { |
|||
assert(result > 0); |
|||
} body { |
|||
if (condition) |
|||
return 42; |
|||
// assert(false) is never stripped from the code, it generates an |
|||
// error in debug builds, and it becomes a HALT instruction in |
|||
// -release mode. |
|||
// |
|||
// It's used as a mark by the D type system. If you remove this |
|||
// line the compiles gives an error: |
|||
// |
|||
// Error: function assertions.foo no return exp; |
|||
// or assert(0); at end of function |
|||
assert(false, "This can't happen."); |
|||
} |
|||
void main() pure { |
|||
int x = foo(true); |
|||
// A regular assertion, it throws an error. |
|||
// Use -release to disable it. |
|||
// It can be used in nothrow functions. |
|||
assert(x == 42, "x is not 42"); |
|||
// This throws an exception and it can't be disabled. |
|||
// There are some different versions of this lazy function. |
|||
enforce(x == 42, "x is not 42"); |
|||
}</syntaxhighlight> |
|||
=={{header|Dart}}== |
|||
=== Assert === |
|||
<syntaxhighlight lang="javascript"> |
|||
main() { |
|||
var i = 42; |
|||
assert( i == 42 ); |
|||
} |
|||
</syntaxhighlight> |
|||
=== 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() { |
|||
int i=42; |
|||
int j=41; |
|||
test('i equals 42?', (){ |
|||
expect( i, equals(42) ); |
|||
}); |
|||
test('j equals 42?', (){ |
|||
expect( j, equals(42) ); |
|||
}); |
|||
}</syntaxhighlight> |
|||
=={{header|Delphi}}== |
|||
<syntaxhighlight lang="delphi">Assert(a = 42);</syntaxhighlight> |
|||
If an assertion fails, EAssertionFailed exception is raised. |
|||
The generation of assertion code can be disabled by compiler directive |
|||
<syntaxhighlight lang="delphi">{$ASSERTIONS OFF}</syntaxhighlight> |
|||
Here is a simple console demo app which raises and handles assertion exception: |
|||
<syntaxhighlight lang="delphi">program TestAssert; |
|||
{$APPTYPE CONSOLE} |
|||
{.$ASSERTIONS OFF} // remove '.' to disable assertions |
|||
uses |
|||
SysUtils; |
|||
var |
|||
a: Integer; |
|||
begin |
|||
try |
|||
Assert(a = 42); |
|||
except |
|||
on E:Exception do |
|||
Writeln(E.Classname, ': ', E.Message); |
|||
end; |
|||
Readln; |
|||
end.</syntaxhighlight> |
|||
=={{header|DWScript}}== |
|||
Simple assertion, with a custom (optional) message |
|||
<syntaxhighlight lang="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">procedure UniversalAnswer(var a : Integer); |
|||
require |
|||
a = 42; |
|||
begin |
|||
// code here |
|||
ensure |
|||
a = 42; |
|||
end;</syntaxhighlight> |
|||
=={{header|Dyalect}}== |
|||
Dyalect has a built-in "assert" function: |
|||
<syntaxhighlight lang="dyalect">var x = 42 |
|||
assert(42, x)</syntaxhighlight> |
|||
This function throws an exception if assertion fails. |
|||
<lang d>import std.string; |
|||
void main() { |
|||
int a = readln().chomp().atoi(); |
|||
assert(a == 42, "You did not input 42!"); |
|||
}</lang> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
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: |
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 |
require(a == 42, "The Answer is Wrong.") # supplied message |
||
require(a == 42, fn { `Off by ${a - 42}.` }) # computed only on failure</ |
require(a == 42, fn { `Off by ${a - 42}.` }) # computed only on failure</syntaxhighlight> |
||
=={{header|EchoLisp}}== |
|||
<syntaxhighlight lang="lisp"> |
|||
(assert (integer? 42)) → #t ;; success returns true |
|||
;; error and return to top level if not true; |
|||
(assert (integer? 'quarante-deux)) |
|||
⛔ error: assert : assertion failed : (#integer? 'quarante-deux) |
|||
;; assertion with message (optional) |
|||
(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}}== |
|||
<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}}== |
=={{header|Eiffel}}== |
||
Line 113: | Line 634: | ||
File called main.e: |
File called main.e: |
||
< |
<syntaxhighlight lang="eiffel">class MAIN |
||
creation main |
creation main |
||
feature main is |
feature main is |
||
Line 124: | Line 645: | ||
test.assert(io.last_integer); |
test.assert(io.last_integer); |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
Another file called test.e: |
Another file called test.e: |
||
< |
<syntaxhighlight lang="eiffel">class TEST |
||
feature assert(val: INTEGER) is |
feature assert(val: INTEGER) is |
||
require |
require |
||
Line 133: | Line 654: | ||
print("Thanks for the 42!%N"); |
print("Thanks for the 42!%N"); |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Elixir}}== |
|||
<syntaxhighlight lang="elixir">ExUnit.start |
|||
defmodule AssertionTest do |
|||
use ExUnit.Case |
|||
def return_5, do: 5 |
|||
test "not equal" do |
|||
assert 42 == return_5 |
|||
end |
|||
end</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1) test not equal (AssertionTest) |
|||
test.exs:8 |
|||
Assertion with == failed |
|||
code: 42 == return_5 |
|||
lhs: 42 |
|||
rhs: 5 |
|||
stacktrace: |
|||
test.exs:9: (test) |
|||
Finished in 0.1 seconds (0.1s on load, 0.01s on tests) |
|||
1 test, 1 failure |
|||
Randomized with seed 869000 |
|||
</pre> |
|||
=={{header|Emacs Lisp}}== |
|||
<syntaxhighlight lang="lisp">(require 'cl-lib) |
|||
(let ((x 41)) |
|||
(cl-assert (= x 42) t "This shouldn't happen"))</syntaxhighlight> |
|||
=={{header|Erlang}}== |
=={{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. |
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 |
42 |
||
2> N = 43. |
2> N = 43. |
||
Line 146: | Line 704: | ||
** exception error: no match of right hand side value 42 |
** exception error: no match of right hand side value 42 |
||
5> 42 = N. |
5> 42 = N. |
||
42</ |
42</syntaxhighlight> |
||
As such, the behavior of Erlang's assignment operator is extremely similar to a regular <tt>assert</tt> in other languages. |
As such, the behavior of Erlang's assignment operator is extremely similar to a regular <tt>assert</tt> in other languages. |
||
=={{header|Euphoria}}== |
|||
<syntaxhighlight lang="euphoria">type fourty_two(integer i) |
|||
return i = 42 |
|||
end type |
|||
fourty_two i |
|||
i = 41 -- type-check failure</syntaxhighlight> |
|||
=={{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) |
|||
test 43</syntaxhighlight> |
|||
For additional information about assertions in .NET, see [[#C# and Visual Basic .NET]] |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Throw an exception if the value on the top of the stack is not equal to 42: |
Throw an exception if the value on the top of the stack is not equal to 42: |
||
< |
<syntaxhighlight lang="factor">USING: kernel ; |
||
42 assert=</ |
42 assert=</syntaxhighlight> |
||
=={{header|FBSL}}== |
|||
One needs to DECLARE the asserter variable at the top of script. |
|||
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 |
|||
FUNCTION Assert(expression) |
|||
DIM cmd AS STRING = "DIM asserter AS INTEGER = (" & expression & ")" |
|||
EXECLINE(cmd, 1) |
|||
IF asserter = 0 THEN PRINT "Assertion: ", expression, " failed" |
|||
END FUNCTION |
|||
Assert("1<2") |
|||
Assert("1>2") |
|||
PAUSE</syntaxhighlight> |
|||
Output |
|||
<pre>Assertion: 1>2 failed |
|||
Press any key to continue...</pre> |
|||
=={{header|Forth}}== |
|||
<syntaxhighlight lang="fsharp">variable a |
|||
: assert a @ 42 <> throw ; |
|||
41 a ! assert</syntaxhighlight> |
|||
=={{header|FreeBASIC}}== |
|||
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
|||
' requires compilation with -g switch |
|||
Dim a As Integer = 5 |
|||
Assert(a = 6) |
|||
'The rest of the code will not be executed |
|||
Print a |
|||
Sleep</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
assert.bas(5): assertion failed at __FB_MAINPROC__: a =6 |
|||
</pre> |
|||
=={{header|GAP}}== |
|||
<syntaxhighlight lang="gap"># See section 7.5 of reference manual |
|||
# GAP has assertions levels. An assertion is tested if its level |
|||
# is less then the global level. |
|||
# Set global level |
|||
SetAssertionLevel(10); |
|||
a := 1; |
|||
Assert(20, a > 1, "a should be greater than one"); |
|||
# nothing happens |
|||
a := 1; |
|||
Assert(4, a > 1, "a should be greater than one"); |
|||
# error |
|||
# Show current global level |
|||
AssertionLevel(); |
|||
# 10</syntaxhighlight> |
|||
=={{header|F_Sharp|F#}}== |
|||
F# provides an ''assert'' function that is only enabled when the program is compiled with ''DEBUG'' defined. |
|||
<lang fsharp>let f x = |
|||
assert (x > 1) |
|||
x</lang> |
|||
=={{header|Go}}== |
=={{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. |
|||
<lang go>package main |
|||
<syntaxhighlight lang="go">package main |
|||
func main() { |
func main() { |
||
Line 169: | Line 806: | ||
panic(42) |
panic(42) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
panic: 42 |
|||
panic PC=0x2b772d1a1048 |
panic PC=0x2b772d1a1048 |
||
Line 181: | Line 819: | ||
runtime.mainstart() |
runtime.mainstart() |
||
runtime.goexit /pool/go/src/pkg/runtime/proc.c:148 |
runtime.goexit /pool/go/src/pkg/runtime/proc.c:148 |
||
runtime.goexit() |
runtime.goexit() |
||
</pre> |
|||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
<lang |
<syntaxhighlight lang="groovy">def checkTheAnswer = { |
||
assert |
assert it == 42 : "This: " + it + " is not the answer!" |
||
}</syntaxhighlight> |
|||
assert f instanceof Closure : "f was not a closure! f: ${f}" |
|||
f(x) |
|||
}</lang> |
|||
Test program: |
Test program: |
||
<lang |
<syntaxhighlight lang="groovy">println "before 42..." |
||
checkTheAnswer(42) |
|||
try { println doSomething(-1, 50) } catch (Throwable t) { println t.message } |
|||
println "before 'Hello Universe'..." |
|||
try { println doSomething(-1, null) } catch (Throwable t) { println t.message }</lang> |
|||
checkTheAnswer("Hello Universe")</syntaxhighlight> |
|||
Output: |
Output: |
||
<pre>before 42... |
|||
<pre>3.141592653589793 |
|||
before 'Hello Universe'... |
|||
f was not a closure! f: 50. Expression: (f instanceof groovy.lang.Closure). Values: f = 50 |
|||
java.lang.AssertionError: This: Hello Universe is not the answer!. Expression: (it == 42). Values: it = Hello Universe |
|||
at ConsoleScript80$_run_closure1.doCall(ConsoleScript80:2) |
|||
at ConsoleScript80.run(ConsoleScript80:8)</pre> |
|||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import Control.Exception |
||
main = let a = someValue in |
main = let a = someValue in |
||
assert (a == 42) -- throws AssertionFailed when a is not 42 |
assert (a == 42) -- throws AssertionFailed when a is not 42 |
||
somethingElse -- what to return when a is 42</ |
somethingElse -- what to return when a is 42</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
<lang Icon>... |
|||
<syntaxhighlight lang="icon">... |
|||
runerr(n,( expression ,"Assertion/error - message.")) # Throw (and possibly trap) an error number n if expression succeeds. |
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. |
stop(( expression ,"Assertion/stop - message.")) # Terminate program if expression succeeds. |
||
...</ |
...</syntaxhighlight> |
||
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: |
|||
=={{header|Java}}== |
|||
<lang java5>public static void main(String[] args){ |
|||
<syntaxhighlight lang="icon"> |
|||
int a; |
|||
$define DEBUG 1 # this allows the assertions to go through |
|||
//...input or change a here |
|||
assert a == 42;//throws an AssertionError when a is not 42 |
|||
procedure check (a) |
|||
assert a == 42 : "Error message"; //throws an AssertionError |
|||
if DEBUG then stop (42 = a, " is invalid value for 'a'") |
|||
//when a is not 42 with "Error message" for the message |
|||
write (a) |
|||
//the error message can be any non-void expression |
|||
end |
|||
}</lang> |
|||
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. |
|||
procedure main () |
|||
check (10) |
|||
check (42) |
|||
check (12) |
|||
end |
|||
</syntaxhighlight> |
|||
This produces the output: |
|||
<pre> |
|||
10 |
|||
42 is invalid value for 'a' |
|||
</pre> |
|||
Changing the define to: <code>$define DEBUG &fail</code> turns off the assertion checking. |
|||
=={{header|J}}== |
=={{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 /> |
|||
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. |
|||
<syntaxhighlight lang="java"> |
|||
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(); |
|||
</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"> |
|||
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"> |
|||
function check() { |
|||
try { |
|||
if (isNaN(answer)) throw '$answer is not a number'; |
|||
if (answer != 42) throw '$answer is not 42'; |
|||
} |
|||
catch(err) { |
|||
console.log(err); |
|||
answer = 42; |
|||
} |
|||
finally { console.log(answer); } |
|||
} |
|||
console.count('try'); // 1 |
|||
let answer; |
|||
check(); |
|||
console.count('try'); // 2 |
|||
answer = 'fourty two'; |
|||
check(); |
|||
console.count('try'); // 3 |
|||
answer = 23; |
|||
check(); |
|||
</syntaxhighlight> |
|||
{{out}}<pre> |
|||
try: 1 |
|||
$answer is not a number |
|||
42 |
|||
try: 2 |
|||
$answer is not a number |
|||
42 |
|||
try: 3 |
|||
$answer is not 42 |
|||
42 |
|||
</pre> |
|||
=={{header|jq}}== |
|||
{{works with|jq}} |
|||
'''Works with gojq, the Go implementation of jq''' |
|||
The assertion filters defined here are designed so that assertions |
|||
intended for development or testing could be left in-place, possibly |
|||
even in production code. |
|||
'''Highlights''' |
|||
* The input to every assertion filter is always passed through without alteration. |
|||
* If assertion checking is turned on, then an assertion violation |
|||
simply results in an error message being emitted on STDERR ("standard error"). |
|||
* Assertions are only checked if the environment variable JQ_ASSERT |
|||
is set (see below for how to turn assertion checking on or off). |
|||
* Pinpointing the occurrence of an assertion violation by using $__loc__ is supported, |
|||
provided your implementation of jq includes this function. |
|||
The assertion checking filters defined here are as follows: |
|||
* assert(x) |
|||
* assert(x; msg) |
|||
* asserteq(x; y; msg) |
|||
<br> |
|||
where: |
|||
* msg determines the message that is printed as part of an assertion violation warning; it would typically be specified as a string or the $__loc__ object if your jq supports it. |
|||
<br> |
|||
'''JQ_ASSERT''' |
|||
Here is a table indicating how the JQ_ASSERT environment variable can be set or unset in various contexts: |
|||
<pre> |
|||
SHELL SET UNSET |
|||
sh bash (etc) export JQ_ASSERT=1 unset JQ_ASSERT |
|||
fish set -x JQ_ASSERT 1 set -u JQ_ASSERT |
|||
csh, tcsh setenv JQ_ASSERT 1 unsetenv JQ_ASSERT |
|||
Windows/DOS SET JQ_ASSERT=1 set JQ_ASSERT= |
|||
Windows: Start > Control Panel > System > Advanced > Environment Variables |
|||
</pre> |
|||
See also the example below for how to set it on a per-invocation basis. |
|||
'''assert.jq''' |
|||
<syntaxhighlight lang="jq">def assert(exp; $msg): |
|||
def m: $msg | if type == "string" then . else [.[]] | join(":") end; |
|||
if env.JQ_ASSERT then |
|||
(exp as $e | if $e then . else . as $in | "assertion violation @ \(m) => \($e)" | debug | $in end) |
|||
else . end; |
|||
def assert(exp): |
|||
if env.JQ_ASSERT then |
|||
(exp as $e | if $e then . else . as $in | "assertion violation: \($e)" | debug | $in end) |
|||
else . end; |
|||
def asserteq(x;y;$msg): |
|||
def m: $msg | if type == "string" then . else [.[]] | join(":") end; |
|||
def s: (if $msg then m + ": " else "" end) + "\(x) != \(y)"; |
|||
if env.JQ_ASSERT then |
|||
if x == y then . |
|||
else . as $in | "assertion violation @ \(s)" | debug | $in |
|||
end |
|||
else . end; |
|||
</syntaxhighlight> |
|||
'''Example''' |
|||
<syntaxhighlight lang="jq"> |
|||
# File: example.jq |
|||
# This example assumes the availability of the $__loc__ function |
|||
# and that assert.jq is in the same directory as example.jq. |
|||
include "assert" {search: "."}; |
|||
def test: |
|||
"This is an input" |
|||
| 0 as $x |
|||
| assert($x == 42; $__loc__), |
|||
asserteq($x; 42; $__loc__); |
|||
test</syntaxhighlight> |
|||
'''Invocation''' |
|||
JQ_ASSERT=1 jq -n -f example.jq |
|||
In the output, the DEBUG line above appears on stderr. |
|||
{{out}} |
|||
<pre> |
|||
["DEBUG:","assertion violation @ <top-level>:16 => false"] |
|||
"This is an input" |
|||
["DEBUG:","assertion violation @ <top-level>:17: 0 != 42"] |
|||
"This is an input" |
|||
</pre> |
|||
=={{header|Julia}}== |
|||
<syntaxhighlight lang="julia">const x = 5 |
|||
# @assert macro checks the supplied conditional expression, with the expression |
|||
# returned in the failed-assertion message |
|||
@assert x == 42 |
|||
# ERROR: LoadError: AssertionError: x == 42 |
|||
# Julia also has type assertions of the form, x::Type which can be appended to |
|||
# variable for type-checking at any point |
|||
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. |
|||
<syntaxhighlight lang="kotlin">fun main() { |
|||
val a = 42 |
|||
assert(a == 43) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Exception in thread "main" java.lang.AssertionError: Assertion failed |
|||
at AssertKt.main(assert.kt:5) |
|||
</pre> |
|||
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 |
|||
val fullName = "$firstName $lastName" |
|||
check(fullName.contains(" ")) { "fullname was expected to have a space...?" } // IllegalStateException |
|||
return fullName |
|||
}</syntaxhighlight> |
|||
=={{header|Lasso}}== |
|||
<syntaxhighlight lang="lasso">local(a) = 8 |
|||
fail_if( |
|||
#a != 42, |
|||
error_code_runtimeAssertion, |
|||
error_msg_runtimeAssertion + ": #a is not 42" |
|||
)</syntaxhighlight> |
|||
{{out}} |
|||
<pre>-9945 Runtime assertion: #a is not 42</pre> |
|||
=={{header|Liberty BASIC}}== |
|||
Liberty BASIC has no exceptions or user-defined error messages, |
|||
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 |
|||
print "passed" |
|||
a=41 |
|||
call assert a=42 |
|||
print "failed (we never get here)" |
|||
end |
|||
sub assert cond |
|||
if cond=0 then 'simulate error, mentioning "AssertionFailed" |
|||
AssertionFailed(-1)=0 |
|||
end if |
|||
end sub |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
passed |
|||
</pre> |
|||
Stops with error message |
|||
{{out}} |
|||
<pre> |
|||
RuntimeError: Subscript out of range: -1, AssertionFailed() |
|||
</pre> |
|||
=={{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 |
|||
if not voidP(message) then _player.alert(message) |
|||
abort -- exits from current call stack, i.e. also from the caller function |
|||
end if |
|||
end |
|||
-- anywhere in the code |
|||
on test |
|||
x = 42 |
|||
assert(x=42, "Assertion 'x=42' failed") |
|||
put "this shows up" |
|||
x = 23 |
|||
assert(x=42, "Assertion 'x=42' failed") |
|||
put "this will never show up" |
|||
end</syntaxhighlight> |
|||
=={{header|Lisaac}}== |
=={{header|Lisaac}}== |
||
< |
<syntaxhighlight lang="lisaac">? { n = 42 };</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">a = 5 |
||
assert (a == 42) |
assert (a == 42) |
||
assert (a == 42,'\''..a..'\' is not the answer to life, the universe, and everything')</ |
assert (a == 42,'\''..a..'\' is not the answer to life, the universe, and everything')</syntaxhighlight> |
||
=={{header| |
=={{header|M2000 Interpreter}}== |
||
M2000 use Error to produce error, Try variable {} and Try {} to capture errors, and return a number from a function when function called as module (zero means no error). |
|||
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. |
|||
<lang MATLAB>assert(x == 42,'x = %d, not 42.',x);</lang> |
|||
=====Making own logging for errors===== |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Module Assert { |
|||
\\ This is a global object named Rec |
|||
Global Group Rec { |
|||
Private: |
|||
document doc$="Error List at "+date$(today)+" "+time$(now)+{ |
|||
} |
|||
Public: |
|||
lastfilename$="noname.err" |
|||
Module Error(a$) { |
|||
if a$="" then exit |
|||
.doc$<=" "+a$+{ |
|||
} |
|||
flush error |
|||
} |
|||
Module Reset { |
|||
Clear .doc$ |
|||
} |
|||
Module Display { |
|||
Report .doc$ |
|||
} |
|||
Module SaveIt { |
|||
.lastfilename$<=replace$("/", "-","Err"+date$(today)+str$(now, "-nn-mm")+".err") |
|||
Save.Doc .doc$,.lastfilename$ |
|||
} |
|||
} |
|||
Module Checkit { |
|||
Function Error1 (x) { |
|||
if x<10 then Print "Normal" : exit |
|||
=130 ' error code |
|||
} |
|||
Call Error1(5) |
|||
Try ok { |
|||
Call Error1(100) |
|||
} |
|||
If not Ok then Rec.Error Error$ : Flush Error |
|||
Test "breakpoint A" ' open Control form, show code as executed, press next or close it |
|||
Try { |
|||
Test |
|||
Report "Run this" |
|||
Error "Hello" |
|||
Report "Not run this" |
|||
} |
|||
Rec.Error Error$ |
|||
Module Error1 (x) { |
|||
if x<10 then Print "Normal" : exit |
|||
Error "Big Error" |
|||
} |
|||
Try ok { |
|||
Error1 100 |
|||
} |
|||
If Error then Rec.Error Error$ |
|||
} |
|||
Checkit |
|||
Rec.Display |
|||
Rec.SaveIt |
|||
win "notepad.exe", dir$+Rec.lastfilename$ |
|||
} |
|||
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">a := 5: |
|||
ASSERT( a = 42 ); |
|||
ASSERT( a = 42, "a is not the answer to life, the universe, and everything" );</syntaxhighlight> |
|||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
|||
<syntaxhighlight lang="mathematica">Assert[var===42]</syntaxhighlight> |
|||
=={{header|MATLAB}} / {{header|Octave}}== |
|||
<syntaxhighlight lang="matlab">assert(x == 42,'x = %d, not 42.',x);</syntaxhighlight> |
|||
Sample Output: |
Sample Output: |
||
< |
<syntaxhighlight lang="matlab">x = 3; |
||
assert(x == 42,'Assertion Failed: x = %d, not 42.',x); |
assert(x == 42,'Assertion Failed: x = %d, not 42.',x); |
||
??? Assertion Failed: x = 3, not 42. |
??? Assertion Failed: x = 3, not 42. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Metafont}}== |
=={{header|Metafont}}== |
||
Line 251: | Line 1,260: | ||
Metafont has no really an assert built in, but it can easily created: |
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 |
This <code>assert</code> macro uses the <code>errmessage</code> built in to show the "error". The |
||
Line 258: | Line 1,267: | ||
Usage example: |
Usage example: |
||
< |
<syntaxhighlight lang="metafont">n := 41; |
||
assert(n=42); |
assert(n=42); |
||
message "ok";</ |
message "ok";</syntaxhighlight> |
||
Output (failed assertion): |
Output (failed assertion): |
||
Line 272: | Line 1,281: | ||
?</pre> |
?</pre> |
||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
<code>ASSERT</code> is a pragma, that creates a run-time error if it returns <code>FALSE</code>. |
<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. |
Assertions can be ignored in the compiler by using the <code>-a</code> switch. |
||
=={{header| |
=={{header|Nanoquery}}== |
||
<syntaxhighlight lang="nanoquery">a = 5 |
|||
<lang Nimrod>var a = 42 |
|||
assert(a |
assert (a = 42)</syntaxhighlight> |
||
Assertions may be disabled by compiling with --assertions:off. |
|||
=={{header|Nemerle}}== |
|||
A basic assertion uses the <tt>assert</tt> keyword: |
|||
<syntaxhighlight lang="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">using Nemerle.Assertions; |
|||
class SampleClass |
|||
{ |
|||
public SomeMethod (input : list[int]) : int |
|||
requires input.Length > 0 // requires keyword indicates precondition, |
|||
// there can be more than one condition per method |
|||
{ ... } |
|||
public AnotherMethod (input : string) : list[char] |
|||
ensures value.Length > 0 // ensures keyword indicates postcondition |
|||
{ ... } // value is a special symbol that indicates the method's return value |
|||
}</syntaxhighlight> |
|||
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]. |
|||
=={{header|NGS}}== |
|||
Assertions in NGS follow the general design of the language: return the original value, use patterns. |
|||
In the examples below, wherever 42 is a parameter by itself: |
|||
* better exception with expected and actual value is produced |
|||
* 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">a = 42 |
|||
assert(a==42) |
|||
assert(a, 42) |
|||
assert(a==42, "Not 42!") |
|||
assert(a, 42, "Not 42!")</syntaxhighlight> |
|||
=={{header|Nim}}== |
|||
In Nim there are two main ways to check assertions. |
|||
<syntaxhighlight lang="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">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 |
|||
a: INTEGER; |
|||
BEGIN |
|||
a := 40; |
|||
ASSERT(a = 42); |
|||
END Assertions. |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
Runtime error: assertion failed (0) on line 6 in module Assertions |
|||
In procedure Assertions.%main |
|||
called from MAIN |
|||
</pre> |
|||
=={{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) { |
|||
a := args[0]->ToInt(); |
|||
Runtime->Assert(a = 42); |
|||
}; |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
For use within an Objective-C method: |
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: |
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. |
Within a regular C function you should use <code>NSCAssert</code> or <code>NSCAssert''N''</code> instead. |
||
Line 297: | Line 1,390: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let a = get_some_value () in |
||
assert (a = 42); (* throws Assert_failure when a is not 42 *) |
assert (a = 42); (* throws Assert_failure when a is not 42 *) |
||
(* evaluate stuff to return here when a is 42 *)</ |
(* evaluate stuff to return here when a is 42 *)</syntaxhighlight> |
||
It is possible to compile with the parameter <code>-noassert</code> then the compiler won't compile the assertion checks. |
It is possible to compile with the parameter <code>-noassert</code> then the compiler won't compile the assertion checks. |
||
=={{header|Oforth}}== |
|||
In Oforth, assertions are handled as tests. |
|||
Assertions are checked only if oforth is launched using --a command line. Default value is to not check assertions. |
|||
If an assertion is ko (and if oforth is launched using --a), an exception is raised. |
|||
<syntaxhighlight lang="oforth">: testInteger(n, m) |
|||
assert: [ n isInteger ] |
|||
assert: [ n 42 == ] |
|||
System.Out "Assertions are ok, parameters are : " << n << ", " << m << cr ;</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
testInteger(41, 43) |
|||
[1:interpreter] ExRuntime : Assertion failed into <#testInteger> |
|||
testInteger(42, 43) |
|||
Assertions are ok, parameters are : 42, 43 |
|||
</pre> |
|||
=={{header|Ol}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
(define i 24) |
|||
(assert i ===> 42) |
|||
; or |
|||
(assert (= i 42)) |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> |
|||
Welcome to Otus Lisp 2.1-2486-481fd919 |
|||
type ',help' to help, ',quit' to end session. |
|||
> (define i 24) |
|||
;; Defined i |
|||
> (assert i ===> 42) |
|||
assertion error: |
|||
i must be 42 |
|||
> (assert (= i 42)) |
|||
assertion error: |
|||
(= i 42) is not a true |
|||
</pre> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
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). |
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} |
proc {PrintNumber N} |
||
N=42 %% assert |
N=42 %% assert |
||
Line 313: | Line 1,451: | ||
in |
in |
||
{PrintNumber 42} %% ok |
{PrintNumber 42} %% ok |
||
{PrintNumber 11} %% throws </ |
{PrintNumber 11} %% throws </syntaxhighlight> |
||
Output: |
Output: |
||
Line 324: | Line 1,462: | ||
%**-------------------------------------------------------------- |
%**-------------------------------------------------------------- |
||
</pre> |
</pre> |
||
=={{header|PARI/GP}}== |
|||
PARI can use any of the usual C methods for making assertions. GP has no built-in assertions. |
|||
{{trans|C}} |
|||
<syntaxhighlight lang="c">#include <assert.h> |
|||
#include <pari/pari.h> |
|||
void |
|||
test() |
|||
{ |
|||
GEN a; |
|||
// ... input or change a here |
|||
assert(equalis(a, 42)); /* Aborts program if a is not 42, unless the NDEBUG macro was defined */ |
|||
}</syntaxhighlight> |
|||
More common is the use of <code>pari_err_BUG</code> in such cases: |
|||
<syntaxhighlight lang="c">if (!equalis(a, 42)) pari_err_BUG("this_function_name (expected a = 42)");</syntaxhighlight> |
|||
=={{header|Pascal}}== |
|||
See [[Assertions#Delphi | Delphi]] |
|||
=={{header|PascalABC.NET}}== |
|||
Assert procedure works only in Debug mode. In Release all Assert calls are ignored. It is impossible to handle assertion exception. |
|||
<syntaxhighlight lang="delphi"> |
|||
begin |
|||
var a := 3; |
|||
Assert(a = 3); |
|||
Assert(a = 4, 'Bad assert!'); |
|||
end. |
|||
</syntaxhighlight> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
While not exactly an assertion, a common Perl idiom is to use <code> |
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. |
||
<lang perl>open my $fh, '<', 'file' or die "Cannot open file: $!\n"; # $! contains the error message from the last error</lang> |
|||
<syntaxhighlight lang="perl">print "Give me a number: "; |
|||
Note: the above "or die" idiom is not needed when the "autodie" pragma is in use: |
|||
chomp(my $a = <>); |
|||
<lang perl>use autodie; |
|||
open my $fh, '<', 'file'; # automatically throws an exception on failure</lang> |
|||
Another example: |
|||
<lang perl>my $a = 5; |
|||
#...input or change $a here |
|||
$a == 42 or die "Error message\n"; |
$a == 42 or die "Error message\n"; |
||
# or, alternatively: |
|||
# Alternatives |
|||
die "Error message\n" unless $a == 42; |
die "Error message\n" unless $a == 42; |
||
# or: |
|||
die "Error message\n" if not $a == 42; |
die "Error message\n" if not $a == 42; |
||
die "Error message\n" if $a != 42;</syntaxhighlight> |
|||
# or just: |
|||
die "Error message\n" if $a != 42;</lang> |
|||
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: |
Some third-party modules provide other ways of using assertions in Perl: |
||
< |
<syntaxhighlight lang="perl">use Carp::Assert; |
||
assert($a == 42);</ |
assert($a == 42);</syntaxhighlight> |
||
There is also a number of ways to test assertions in test suites, for example: |
There is also a number of ways to test assertions in test suites, for example: |
||
< |
<syntaxhighlight lang="perl">is $a, 42; |
||
ok $a == 42; |
ok $a == 42; |
||
cmp_ok $a, '==', 42, 'The answer should be 42'; |
cmp_ok $a, '==', 42, 'The answer should be 42'; |
||
# etc.</ |
# etc.</syntaxhighlight> |
||
=={{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: |
|||
<!--<syntaxhighlight lang="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> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">type</span> |
|||
<span style="color: #000000;">int42</span> <span style="color: #000000;">i</span> |
|||
<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> |
|||
<!--</syntaxhighlight>--> |
|||
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. |
|||
Note that, under "without type_check", the run-time reserves the right to continue to |
|||
perform limited type checking, for example were the type declared as int42(integer i) |
|||
then ensuring that i is an integer may allow subsequent optimisations to be applied, |
|||
and therefore, despite the compiler directive, integer() could still be enforced even |
|||
though "=42" would not. |
|||
You can also use constants to reduce code output on release versions: |
|||
<!--<syntaxhighlight lang="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> |
|||
<span style="color: #008080;">if</span> <span style="color: #000000;">DEBUG</span> <span style="color: #008080;">then</span> |
|||
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">flag</span> <span style="color: #008080;">then</span> |
|||
<span style="color: #7060A8;">IupMessage</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"check failed"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- or</span> |
|||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- and/or</span> |
|||
<span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- crash/ex.err report, or</span> |
|||
<span style="color: #008080;">trace</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- start debugging</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
|||
<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> |
|||
<!--</syntaxhighlight>--> |
|||
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 |
|||
compiler may be possible, sometimes the calls may need "if DEBUG" around them. Also |
|||
note that, as things stand, the constants 42 and "i is not 42!!" will be created in the |
|||
executable file whatever DEBUG is set to, though again there is nothing to prevent the |
|||
compiler from being enhanced to avoid emitting such unnecessary values, one day. |
|||
Lastly, I find the following trivial idioms to be spectacularly effective in Phix, the |
|||
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">(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> |
|||
<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> |
|||
<!--</syntaxhighlight>--> |
|||
The assert statment is really just shorthand for the crash statement above it, except that |
|||
the error message is optional (defaults to "assertion failure"). |
|||
Again, if the application was run from Edita/Edix, on error it automatically jumps to the |
|||
offending file and line. |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php"><?php |
||
$a = 5 |
$a = 5 |
||
#...input or change $a here |
#...input or change $a here |
||
assert($a == 42) # when $a is not 42, take appropriate actions, |
assert($a == 42) # when $a is not 42, take appropriate actions, |
||
# which is set by assert_options() |
# which is set by assert_options() |
||
?></ |
?></syntaxhighlight> |
||
=={{header|Picat}}== |
|||
Picat does not have a built-in assertion feature; a simple implementation is shown below. Note that predicates and functions must be handled differently: |
|||
* predicates: using <code>call/n</code> |
|||
* functions: using <code>apply/n</code> |
|||
The predicate/function that is tested but be "escaped" by <code>$</code> in order to not be evaluated before the test. |
|||
<syntaxhighlight lang="picat">go => |
|||
% |
|||
% Test predicates |
|||
% |
|||
S = "ablewasiereisawelba", |
|||
assert("test1",$is_palindrome(S)), |
|||
assert_failure("test2",$not is_palindrome(S)), |
|||
assert("test3",$member(1,1..10)), |
|||
assert_failure("test4",$member(1,1..10)), % bad test |
|||
nl, |
|||
% |
|||
% Test functions |
|||
% |
|||
assert("test5",$2+2,4), |
|||
assert_failure("test6",$2+2, 5), |
|||
assert("test7",$to_lowercase("PICAT"),"picat"), |
|||
assert_failure("test8",$sort([3,2,1]),[1,3,2]), |
|||
nl. |
|||
is_palindrome(S) => |
|||
S == S.reverse(). |
|||
% Test a predicate with call/1 |
|||
assert(Name, A) => |
|||
println(Name ++ ": " ++ cond(call(A), "ok", "not ok")). |
|||
assert_failure(Name, A) => |
|||
println(Name ++ ": " ++ cond(not call(A), "ok", "not ok")). |
|||
% Test a function with apply/1 |
|||
assert(Name, A, Expected) => |
|||
println(Name ++ ": " ++ cond(apply(A) == Expected, "ok", "not ok")). |
|||
assert_failure(Name, A, Expected) => |
|||
println(Name ++ ": " ++ cond(apply(A) != Expected , "ok", "not ok")).</syntaxhighlight> |
|||
{{out}} |
|||
<pre>test1: ok |
|||
test2: ok |
|||
test3: ok |
|||
test4: not ok |
|||
test5: ok |
|||
test6: ok |
|||
test7: ok |
|||
test8: ok</pre> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
The '[http://software-lab.de/doc/refA.html#assert assert]' function, in |
The '[http://software-lab.de/doc/refA.html#assert assert]' function, in |
||
combination with the tilde read macro, generates code only in debug mode: |
combination with the tilde read macro, generates code only in debug mode: |
||
<syntaxhighlight lang="picolisp">... |
|||
<lang PicoLisp>... |
|||
~(assert (= N 42)) # Exists only in debug mode |
~(assert (= N 42)) # Exists only in debug mode |
||
...</ |
...</syntaxhighlight> |
||
Other possibilities are either to break into an error handler: |
Other possibilities are either to break into an error handler: |
||
< |
<syntaxhighlight lang="picolisp">(let N 41 |
||
(unless (= N 42) (quit "Incorrect N" N)) ) # 'quit' throws an error |
(unless (= N 42) (quit "Incorrect N" N)) ) # 'quit' throws an error |
||
41 -- Incorrect N |
41 -- Incorrect N |
||
?</ |
?</syntaxhighlight> |
||
or to stop at a debug break point, allowing to continue with the program: |
or to stop at a debug break point, allowing to continue with the program: |
||
< |
<syntaxhighlight lang="picolisp">(let N 41 |
||
(unless (= N 42) (! setq N 42)) ) # '!' is a breakpoint |
(unless (= N 42) (! setq N 42)) ) # '!' is a breakpoint |
||
(setq N 42) # Manually fix the value |
(setq N 42) # Manually fix the value |
||
! # Hit ENTER to leave the breakpoint |
! # Hit ENTER to leave the breakpoint |
||
-> 42</ |
-> 42</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<lang> |
<syntaxhighlight lang="text"> |
||
/* PL/I does not have an assert function as such, */ |
/* PL/I does not have an assert function as such, */ |
||
/* but it is something that can be implemented in */ |
/* but it is something that can be implemented in */ |
||
Line 399: | Line 1,685: | ||
assert(a, 42); |
assert(a, 42); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
{{works with|SWI Prolog}} |
{{works with|SWI Prolog}} |
||
< |
<syntaxhighlight lang="prolog"> |
||
test(A):- |
test(A):- |
||
assertion(A==42). |
assertion(A==42). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
Line 414: | Line 1,700: | ||
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. |
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">Macro Assert(TEST,MSG="Assert: ") |
||
CompilerIf #PB_Compiler_Debugger |
CompilerIf #PB_Compiler_Debugger |
||
If Not (TEST) |
If Not (TEST) |
||
Line 421: | Line 1,707: | ||
EndIf |
EndIf |
||
CompilerEndIf |
CompilerEndIf |
||
EndMacro</ |
EndMacro</syntaxhighlight> |
||
A implementation as defined above could be; |
A implementation as defined above could be; |
||
<syntaxhighlight lang="purebasic">A=42 |
|||
<lang PureBasic>A=42 |
|||
Assert(A=42,"Assert that A=42") |
Assert(A=42,"Assert that A=42") |
||
A=42-1 |
A=42-1 |
||
Assert(A=42)</ |
Assert(A=42)</syntaxhighlight> |
||
Where the second test would fail resulting in a message to the programmer with cause (if given by programmer), code line & file. |
Where the second test would fail resulting in a message to the programmer with cause (if given by programmer), code line & file. |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">a = 5 |
||
#...input or change a here |
#...input or change a here |
||
assert a == 42 # throws an AssertionError when a is not 42 |
assert a == 42 # throws an AssertionError when a is not 42 |
||
assert a == 42, "Error message" # throws an AssertionError |
assert a == 42, "Error message" # throws an AssertionError |
||
# when a is not 42 with "Error message" for the message |
# when a is not 42 with "Error message" for the message |
||
# the error message can be any expression</ |
# the error message can be any expression</syntaxhighlight> |
||
It is possible to turn off assertions by running Python with the <tt>-O</tt> (optimizations) flag. |
It is possible to turn off assertions by running Python with the <tt>-O</tt> (optimizations) flag. |
||
=={{header|QB64}}== |
|||
<syntaxhighlight lang="vb">$ASSERTS:CONSOLE |
|||
DO |
|||
a = INT(RND * 10) |
|||
b$ = myFunc$(a) |
|||
PRINT a, , b$ |
|||
_LIMIT 3 |
|||
LOOP UNTIL _KEYHIT |
|||
FUNCTION myFunc$ (value AS SINGLE) |
|||
_ASSERT value > 0, "Value cannot be zero" |
|||
_ASSERT value <= 10, "Value cannot exceed 10" |
|||
IF value > 1 THEN plural$ = "s" |
|||
myFunc$ = STRING$(value, "*") + STR$(value) + " star" + plural$ + " :-)" |
|||
END FUNCTION</syntaxhighlight> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r">stopifnot(a==42)</syntaxhighlight> |
||
=={{header|Racket}}== |
|||
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">#lang racket |
|||
(define/contract x |
|||
(=/c 42) ; make sure x = 42 |
|||
42) |
|||
(define/contract f |
|||
(-> number? (or/c 'yes 'no)) ; function contract |
|||
(lambda (x) |
|||
(if (= 42 x) 'yes 'no))) |
|||
(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: |
|||
<syntaxhighlight lang="racket">#lang racket |
|||
(define x 80) |
|||
(unless (= x 42) |
|||
(error "a is not 42")) ; will error |
|||
</syntaxhighlight> |
|||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
<syntaxhighlight lang="raku" line>my $a = (1..100).pick; |
|||
$a == 42 or die '$a ain\'t 42';</syntaxhighlight> |
|||
=={{header|REXX}}== |
|||
===version 1=== |
|||
<syntaxhighlight lang="rexx">/* REXX *************************************************************** |
|||
* There's no assert feature in Rexx. That's how I'd implement it |
|||
* 10.08.2012 Walter Pachl |
|||
**********************************************************************/ |
|||
x.=42 |
|||
x.2=11 |
|||
Do i=1 By 1 |
|||
Call assert x.i,42 |
|||
End |
|||
Exit |
|||
assert: |
|||
Parse Arg assert_have,assert_should_have |
|||
If assert_have\==assert_should_have Then Do |
|||
Say 'Assertion fails in line' sigl |
|||
Say 'expected:' assert_should_have |
|||
Say ' found:' assert_have |
|||
Say sourceline(sigl) |
|||
Say 'Look around' |
|||
Trace ?R |
|||
Nop |
|||
Signal Syntax |
|||
End |
|||
Return |
|||
Syntax: Say 'program terminated'</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
Assertion fails in line 8 |
|||
expected: 42 |
|||
found: 11 |
|||
Call assert x.i,42 |
|||
Look around |
|||
Here I enter Say i |
|||
2 |
|||
and then I press just enter |
|||
program terminated |
|||
</pre> |
|||
===version 2=== |
|||
Programming note: this simple version will work better when the '''ASSERT''' be on one line, |
|||
<br>and be without other REXX statements. |
|||
The clauses don't require parentheses, but are used here for clarity. |
|||
The '''ASSERT''' function could be programmed to '''exit''' as one of many |
|||
<br>possible actions. 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 " */ |
|||
gee = 7.00 /* " " " " " GEE " */ |
|||
zee = 26 /* " " " " " ZEE " */ |
|||
call assert (a = 1) |
|||
call assert (b > 0) |
|||
call assert (gee = 7) |
|||
call assert (zee = a & zee>b) |
|||
exit /*stick a fork in it, we're all done. */ |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
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</syntaxhighlight> |
|||
{{out|output|text= when using the internal defaults:}} |
|||
<pre> |
|||
===== ASSERT failure in REXX line 8, the statement is: |
|||
===== call assert (b > 0) |
|||
===== ASSERT failure in REXX line 10, the statement is: |
|||
===== call assert (zee = a & zee>b) |
|||
</pre> |
|||
=={{header|Ring}}== |
|||
<syntaxhighlight lang="ring"> |
|||
x = 42 |
|||
assert( x = 42 ) |
|||
assert( x = 100 ) |
|||
</syntaxhighlight> |
|||
=={{header|RLaB}}== |
=={{header|RLaB}}== |
||
RLaB does not have a special function to deal with assertions. The following workaround will do the trick: |
RLaB does not have a special function to deal with assertions. The following workaround will do the trick: |
||
<syntaxhighlight lang="rlab"> |
|||
<lang RLaB> |
|||
// test if 'a' is 42, and if not stop the execution of the code and print |
// test if 'a' is 42, and if not stop the execution of the code and print |
||
// some error message |
// some error message |
||
Line 452: | Line 1,869: | ||
stop("a is not 42 as expected, therefore I stop until this issue is resolved!"); |
stop("a is not 42 as expected, therefore I stop until this issue is resolved!"); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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}}== |
=={{header|Ruby}}== |
||
This uses test/unit from the standard library. |
|||
{{libheader|test/unit}} |
|||
< |
<syntaxhighlight lang="ruby">require "test/unit/assertions" |
||
include Test::Unit::Assertions |
include Test::Unit::Assertions |
||
Line 467: | Line 1,897: | ||
# Ruby 1.9: e is a MiniTest::Assertion |
# Ruby 1.9: e is a MiniTest::Assertion |
||
puts e |
puts e |
||
end</ |
end</syntaxhighlight> |
||
Output: <pre><42> expected but was |
Output: <pre><42> expected but was |
||
<5>.</pre> |
<5>.</pre> |
||
=={{header|Rust}}== |
|||
<syntaxhighlight lang="rust"> |
|||
let x = 42; |
|||
assert!(x == 42); |
|||
assert_eq!(x, 42); |
|||
</syntaxhighlight> |
|||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
< |
<syntaxhighlight lang="sather">class MAIN is |
||
main is |
main is |
||
i ::= 41; |
i ::= 41; |
||
Line 479: | Line 1,916: | ||
-- ... |
-- ... |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
(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]). |
(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 485: | Line 1,922: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
These two are the same thing, and are tagged <code>@elidable(ASSERTION)</code>: |
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") |
assert(a == 42, "a isn't equal to 42") |
||
assume(a == 42) |
assume(a == 42) |
||
assume(a == 42, "a isn't equal to 42")</ |
assume(a == 42, "a isn't equal to 42")</syntaxhighlight> |
||
The next one does the same thing as above, but it is not tagged. Often used as a pre-condition |
The next one does the same thing as above, but it is not tagged. Often used as a pre-condition |
||
checker on class constructors. |
checker on class constructors. |
||
< |
<syntaxhighlight lang="scala">require(a == 42) |
||
require(a == 42, "a isn't equal to 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 |
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. |
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(a == 42, "a isn't equal to 42")) |
||
println(a.ensuring(_ == 42)) |
println(a.ensuring(_ == 42)) |
||
println(a.ensuring(_ == 42, "a isn't equal to 42"))</ |
println(a.ensuring(_ == 42, "a isn't equal to 42"))</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
Line 506: | Line 1,943: | ||
{{trans|Common Lisp}} |
{{trans|Common Lisp}} |
||
< |
<syntaxhighlight lang="scheme">(let ((x 42)) |
||
(assert (and (integer? x) (= 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}} |
|||
<pre> |
|||
assert_eq: 26 == 42 is false at assertions.sf line 2. |
|||
</pre> |
|||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang="slate">load: 'src/lib/assert.slate'. |
||
define: #n -> 7. |
define: #n -> 7. |
||
assert: n = 42 &description: 'That is not the Answer.'.</ |
assert: n = 42 &description: 'That is not the Answer.'.</syntaxhighlight> |
||
raises an <tt>AssertionFailed</tt> condition (an <tt>Error</tt>). |
raises an <tt>AssertionFailed</tt> condition (an <tt>Error</tt>). |
||
=={{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. |
|||
=={{header|SPARK}}== |
=={{header|SPARK}}== |
||
Line 519: | Line 1,982: | ||
Assertions are analysed statically, before compilation or execution. They can appear in various places: |
Assertions are analysed statically, before compilation or execution. They can appear in various places: |
||
:inline in the code, either |
:inline in the code, either |
||
< |
<syntaxhighlight lang="ada">-# check X = 42;</syntaxhighlight> |
||
::or |
::or |
||
< |
<syntaxhighlight lang="ada">-# assert X = 42;</syntaxhighlight> |
||
:as a precondition on an operation: |
:as a precondition on an operation: |
||
< |
<syntaxhighlight lang="ada">procedure P (X : in out Integer); |
||
--# derives X from *; |
--# derives X from *; |
||
--# pre X = 42;</ |
--# pre X = 42;</syntaxhighlight> |
||
:or as a postcondition on an operation: |
:or as a postcondition on an operation: |
||
< |
<syntaxhighlight lang="ada">procedure P (X : in out Integer); |
||
--# derives X from *; |
--# derives X from *; |
||
--# post X = 42;</ |
--# post X = 42;</syntaxhighlight> |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="ada">X := 7; |
||
--# check X = 42;</ |
--# check X = 42;</syntaxhighlight> |
||
produces the following output: |
produces the following output: |
||
<pre>H1: true . |
<pre>H1: true . |
||
Line 538: | Line 2,001: | ||
C1: false .</pre> |
C1: false .</pre> |
||
which is an unprovable theorem that tells you that there is a guaranteed failure. |
which is an unprovable theorem that tells you that there is a guaranteed failure. |
||
=={{header|Standard ML}}== |
|||
Using exceptions: |
|||
<syntaxhighlight lang="sml">fun assert cond = |
|||
if cond then () else raise Fail "assert" |
|||
val () = assert (x = 42)</syntaxhighlight> |
|||
=={{header|Stata}}== |
|||
Assertions in Stata are limited to checking a property on the observations of a dataset. See '''[http://www.stata.com/help.cgi?assert assert]''' in Stata help. |
|||
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. |
|||
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 |
|||
}</syntaxhighlight> |
|||
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}}== |
|||
<syntaxhighlight lang="swift">var a = 5 |
|||
//...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</syntaxhighlight> |
|||
In release mode assertion checks are turned off. |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
{{tcllib|control}} |
{{tcllib|control}} |
||
< |
<syntaxhighlight lang="tcl">package require control |
||
set x 5 |
set x 5 |
||
control::assert {$x == 42}</ |
control::assert {$x == 42}</syntaxhighlight> |
||
Produces the output: |
Produces the output: |
||
<pre>assertion failed: $x == 42</pre> |
<pre>assertion failed: $x == 42</pre> |
||
{{omit from|gnuplot}} |
|||
=={{header|UNIX Shell}}== |
|||
{{omit from|NSIS}} |
|||
{{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 |
|||
exit 1 |
|||
fi |
|||
} |
|||
x=42 |
|||
assert "$x -eq 42" "that's not the answer" |
|||
((x--)) |
|||
assert "$x -eq 42" "that's not the answer" |
|||
echo "won't get here"</syntaxhighlight> |
|||
=={{header|Vala}}== |
|||
<syntaxhighlight lang="vala">int a = 42; |
|||
int b = 33; |
|||
assert (a == 42); |
|||
assert (b == 42); // will break the program with "assertion failed" error</syntaxhighlight> |
|||
=={{header|VBA}}== |
|||
<syntaxhighlight lang="vb">Sub test() |
|||
Dim a As Integer |
|||
a = 41 |
|||
Debug.Assert a = 42 |
|||
End Sub</syntaxhighlight> |
|||
{{out}} |
|||
When run in the development area executing halts and highlights with yellow background the debug.assert line. |
|||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
====Definition==== |
====Definition==== |
||
< |
<syntaxhighlight lang="vb">sub Assert( boolExpr, strOnFail ) |
||
if not boolExpr then |
if not boolExpr then |
||
Err.Raise vbObjectError + 99999, , strOnFail |
Err.Raise vbObjectError + 99999, , strOnFail |
||
end if |
end if |
||
end sub |
end sub |
||
</syntaxhighlight> |
|||
</lang> |
|||
====Invocation==== |
====Invocation==== |
||
< |
<syntaxhighlight lang="vb">dim i |
||
i = 43 |
i = 43 |
||
Assert i=42, "There's got to be more to life than this!"</ |
Assert i=42, "There's got to be more to life than this!"</syntaxhighlight> |
||
====Output==== |
====Output==== |
||
< |
<syntaxhighlight lang="vbscript">>cscript "C:\foo\assert.vbs" |
||
C:\foo\assert.vbs(3, 3) (null): There's got to be more to life than this!</ |
C:\foo\assert.vbs(3, 3) (null): There's got to be more to life than this!</syntaxhighlight> |
||
=={{header|Visual Basic}}== |
=={{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. |
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}}== |
|||
<lang vb>Debug.Assert i = 42</lang> |
|||
See [[#C# and Visual Basic .NET]]. |
|||
=={{header|V (Vlang)}}== |
|||
{{omit from|PARI/GP}} |
|||
<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="wren">var assertEnabled = true |
|||
var assert = Fn.new { |cond| |
|||
if (assertEnabled && !cond) Fiber.abort("Assertion failure") |
|||
} |
|||
var x = 42 |
|||
assert.call(x == 42) // fine |
|||
assertEnabled = false |
|||
assert.call(x > 42) // no error |
|||
assertEnabled = true |
|||
assert.call(x > 42) // error</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
$ wren assertion.wren |
|||
Assertion failure |
|||
[./assertion line 4] in new(_) block argument |
|||
[./assertion line 12] in (script) |
|||
</pre> |
|||
<br> |
|||
{{libheader|Wren-debug}} |
|||
The above module also provides limited support for assertions. |
|||
<syntaxhighlight lang="wren">import "./debug" for Debug |
|||
var x = 42 |
|||
Debug.assert("x == 42", 4, x == 42) // fine |
|||
Debug.off |
|||
Debug.assert("x > 42", 6, x > 42) // no error |
|||
Debug.on |
|||
Debug.assert("x > 42", 8, x > 42) // error</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
ASSERTION on line 8 labelled 'x > 42' failed. Aborting fiber. |
|||
Assertion failure. |
|||
[./debug line 100] in assert(_,_,_) |
|||
[./assert line 8] in (script) |
|||
</pre> |
|||
=={{header|XPL0}}== |
|||
XPL0 does not have an assert command. The equivalent is usually |
|||
synthesized something like this. |
|||
<syntaxhighlight lang="xpl0">proc Fatal(Str); \Display error message and terminate program |
|||
char Str; |
|||
[\return; uncomment this if "assertions" are to be disabled |
|||
SetVid(3); \set normal text display if program uses graphics |
|||
Text(0, Str); \display error message |
|||
ChOut(0, 7); \sound the bell |
|||
exit 1; \terminate the program; pass optional error code to DOS |
|||
]; |
|||
if X#42 then Fatal("X#42");</syntaxhighlight> |
|||
=={{header|Yabasic}}== |
|||
<syntaxhighlight lang="yabasic">sub assert(a) |
|||
if not a then |
|||
error "Assertion failed" |
|||
end if |
|||
end sub |
|||
assert(myVar = 42)</syntaxhighlight> |
|||
=={{header|Zig}}== |
|||
<syntaxhighlight lang="zig">const assert = @import("std").debug.assert; |
|||
pub fn main() void { |
|||
const n: i64 = 43; |
|||
assert(n == 42); // On failure, an `unreachable` is reached |
|||
}</syntaxhighlight> |
|||
Zig's assert gives a stack trace for debugging on failure. |
|||
=={{header|Z80 Assembly}}== |
|||
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}} |
|||
<pre> |
|||
Stack trace for VM#1 (): |
|||
Cmd.__constructor addr:38 args(0) reg(1) |
|||
startup.__constructor addr:2242 args(0) reg(1) ER |
|||
startup.__constructor addr:2178 args(0) reg(22) |
|||
Exception thrown: AssertionError(I wanted 42!) |
|||
</pre> |
|||
=={{header|zonnon}}== |
|||
<syntaxhighlight lang="zonnon"> |
|||
module Assertions; |
|||
var |
|||
a: integer; |
|||
begin |
|||
a := 40; |
|||
assert(a = 42,100) |
|||
end Assertions. |
|||
</syntaxhighlight> |
|||
{{omit from|gnuplot}} |
|||
{{omit from|NSIS}} |
Latest revision as of 19:04, 17 May 2024
You are encouraged to solve this task according to the task description, using any language you may know.
Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
- Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
11l
V a = 5
assert(a == 42)
assert(a == 42, ‘Error message’)
68000 Assembly
CMP.L #42,D0
BEQ continue
ILLEGAL ;causes an immediate jump to the illegal instruction vector.
continue:
; rest of program
Ada
Using pragma Assert:
pragma Assert (A = 42, "Oops!");
The behavior of pragma is controlled by pragma Assertion_Policy. Another way is to use the predefined package Ada.Assertions:
with Ada.Assertions; use 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.
procedure Find_First
(List : in Array_Type;
Value : in Integer;
Found : out Boolean;
Position : out Positive) with
Depends => ((Found, Position) => (List, Value)),
Pre => (List'Length > 0),
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.
Aime
integer x;
x = 41;
if (x != 42) {
error("x is not 42");
}
Executing the program will produce on standard error:
aime: assert: 5: x is not 42
ALGOL 68
The "Revised Report on the Algorithmic Language - ALGOL 68" suggest that ASSERT may be made available by a particular implementation, quote: "Pragmats may ... convey to the implementation some piece of information affecting some aspect of the meaning of the program which is not defined by this Report,..."
Example given[1]:
INT a, b; read((a, b)) PR ASSERT a >= 0 & b > 0 PR;
This works with neither ELLA ALGOL 68 nor ALGOL 68G.
The standard alternative would be to implement the assertions as an exception as per the Exceptions sample code.
In ELLA ALGOL 68 the ASSERT is implemented as an operator in the environment prelude:
OP ASSERT = (VECTOR [] CHAR assertion,BOOL valid) VOID:
IF NOT valid
THEN type line on terminal(assertion);
terminal error( 661 {invalid assertion } )
FI;
And can be "USEd" as follows:
PROGRAM assertions CONTEXT VOID
USE standard,environment
BEGIN
INT a := 43;
"Oops!" ASSERT ( a = 42 )
END
FINISH
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.
begin
integer a;
a := 43;
assert a = 42;
write( "this won't appear" )
end.
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');
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);
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);
You can’t catch an assertion failure using a try/catch block even though it is logged as an exception.
Arturo
a: 42
ensure [a = 42]
AutoHotkey
Exceptions
a := 42
Assert(a > 10)
Assert(a < 42) ; throws exception
Assert(bool){
If !bool
throw Exception("Expression false", -1)
}
Legacy versions
if (a != 42)
{
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
}
AWK
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
assert(meaning == 42, "Integer mathematics failed")
assert(meaning == 42)
meaning = strtonum("42 also known as forty-two")
assert(meaning == 42, "Built-in function failed")
meaning = "42"
assert(meaning == 42, "Dynamic type conversion failed")
meaning = 6 * 9
assert(meaning == 42, "Ford Prefect's experiment failed")
print "That's all folks"
exit
}
# Errormsg is optional, displayed if assertion fails
function assert(cond, errormsg){
if (!cond) {
if (errormsg != "") print errormsg
exit 1
}
}
The above example produces the output below, and sets the program's exit code to 1 (the default is 0)
Ford Prefect's experiment failed
Axe
A=42??Returnʳ
BASIC
BaCon
' Assertions
answer = assertion(42)
PRINT "The ultimate answer is indeed ", answer
PRINT "Now, expect a failure, unless NDEBUG defined at compile time"
answer = assertion(41)
PRINT answer
END
' Ensure the given number is the ultimate answer
FUNCTION assertion(NUMBER i)
' BaCon can easily be intimately integrated with C
USEH
#include <assert.h>
END USEH
' If the given expression is not true, abort the program
USEC
assert(i == 42);
END USEC
RETURN i
END FUNCTION
- Output:
prompt$ bacon -q assertion.bac && ./assertion Converting 'assertion.bac'... done, 24 lines were processed in 0.006 seconds. Compiling 'assertion.bac'... cc -c assertion.bac.c cc -o assertion assertion.bac.o -lbacon -lm Done, program 'assertion' ready. The ultimate answer is indeed 42 Now, expect a failure, unless NDEBUG defined at compile time assertion: assertion.assertion.h:16: assertion: Assertion `i == 42' failed. ERROR: signal ABORT received - internal error. Try to compile the program with TRAP LOCAL to find the cause. prompt$ bacon -q -o '-DNDEBUG' assertion.bac && ./assertion Converting 'assertion.bac'... done, 24 lines were processed in 0.003 seconds. Compiling 'assertion.bac'... cc -DNDEBUG -c assertion.bac.c cc -o assertion assertion.bac.o -lbacon -lm Done, program 'assertion' ready. The ultimate answer is indeed 42 Now, expect a failure, unless NDEBUG defined at compile time 41
BASIC256
subroutine assert (condition, message)
if not condition then print "ASSERTION FAIED: ";message: throwerror 1
end subroutine
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
BBC BASIC
PROCassert(a% = 42)
END
DEF PROCassert(bool%)
IF NOT bool% THEN ERROR 100, "Assertion failed"
ENDPROC
BQN
BQN has a primitive for logical assertions called Assert(!
).
Called with a single argument, it throws an error if its argument is not 1.
Called with a left argument, it prints the left argument, and then throws an error.
! 2=3 # Failed Error: Assertion error at ! 2=3 # Failed ^ "hello" ! 2=3 # Failed Error: hello at "hello" ! 2=3 # Failed
Brat
squish import :assert :assertions
assert_equal 42 42
assert_equal 13 42 #Raises an exception
C
#include <assert.h>
int main(){
int a;
/* ...input or change a here */
assert(a == 42); /* aborts program when a is not 42, unless the NDEBUG macro was defined */
return 0;
}
To turn off assertions, simply define the NDEBUG macro before where <assert.h> 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:
assert(a == 42 && "Error message");
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.
C# and Visual Basic .NET
.NET provides the Debug.Assert and Trace.Assert methods, which notify TraceListener instances subscribed to the program's trace output if the specified condition is false. Both methods also have overloads that allow a specified string to be added to the default message of the assertion, which consists of "Assertion Failed" and a stack trace for the location of the assertion.
The behavior of a failed assertion is controlled by the listeners in the TraceListeners collection shared by the Debug and Trace classes. By default, the collection contains an instance of the DefaultTraceListener class, which uses functions in the Windows API that notify attached debuggers, if any. Additional behavior depends on the framework version that the application is running in:
- In .NET Core applications, if no debuggers are attached, failed Debug.Assert assertions for non-UI applications terminate the program and write the assertion message to the console, while failed Trace.Assert assertions do not affect execution. In this respect, a failed Debug assertion behaves similarly to an exception.
- In .NET Framework applications, for both types of assertions, a special instance of the Abort-Retry-Ignore message box containing the assertion message is displayed (even with a debugger attached). "Abort" terminates the program; "Retry" switches to the location of the assertion in source code if the application is running in a debugger, or, if none are attached, prompts to launch a just-in-time debugger; and "Ignore" continues execution past the assertion.
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.
using System.Diagnostics; // Debug and Trace are in this namespace.
static class Program
{
static void Main()
{
int a = 0;
Console.WriteLine("Before");
// Always hit.
Trace.Assert(a == 42, "Trace assertion failed");
Console.WriteLine("After Trace.Assert");
// Only hit in debug builds.
Debug.Assert(a == 42, "Debug assertion failed");
Console.WriteLine("After Debug.Assert");
}
}
Imports System.Diagnostics
' Note: VB Visual Studio projects have System.Diagnostics imported by default,
' along with several other namespaces.
Module Program
Sub Main()
Dim a As Integer = 0
Console.WriteLine("Before")
' Always hit.
Trace.Assert(a = 42, "Trace assertion failed: The Answer was incorrect")
Console.WriteLine("After Trace.Assert")
' Only hit in debug builds.
Debug.Assert(a = 42, "Debug assertion failed: The Answer was incorrect")
Console.WriteLine("After Debug.Assert")
End Sub
End Module
- Output (for .NET Core debug builds when outside of a debugger):
Before After Trace.Assert Assertion Failed Debug assertion failed at Program.Main() in FILENAME:line 21
- Output:
In .NET Core applications, this is the output
- when a debugger is attached and is used to continue past both assertions when they fail, or
- in release builds of the program, where the call to Debug.Assert is removed and the Trace.Assert assertion is hit but has no visible effects.
In .NET Framework applications, assertions never show up in the console and so the output is this when a debugger or the "Ignore" option used to continue past the assertions.
Before After Trace.Assert After Debug.Assert
Displaying Trace assertions in console:
To "see" the Trace.Assert assertion, additional TraceListener instances must be subscribed by the program. In the .NET Framework, there are several built-in subclasses of TraceListener, including ConsoleTraceListener, which writes trace messages to the console. In .NET Core, these classes are available starting from .NET Core 3.0.
Subscribing an instance involves adding the following line to the beginning of Main() (with a semicolon in C#, of course ;)
Trace.Listeners.Add(new ConsoleTraceListener())
C++
#include <cassert> // assert.h also works
int main()
{
int a;
// ... input or change a here
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 std::
prefix because it's a macro.
Clojure
(let [i 42]
(assert (= i 42)))
Common Lisp
(let ((x 42))
(assert (and (integerp x) (= 42 x)) (x)))
Component Pascal
Works with BlackBox Component Builder
MODULE Assertions;
VAR
x: INTEGER;
PROCEDURE DoIt*;
BEGIN
x := 41;
ASSERT(x = 42);
END DoIt;
END Assertions.
Assertions.DoIt
Output:
TRAP 0 Assertions.DoIt [0000001DH] Kernel.Call [00001A7CH] .adr INTEGER 1685454913 .kind INTEGER 0 .n INTEGER 0 .p INTEGER 0 .par ARRAY 256 OF INTEGER elements .r REAL 8.70603013185328E+175 .sig POINTER [64760018H] .size INTEGER 2287288 .sp INTEGER 256 .typ POINTER NIL Meta.Item.ParamCallVal [00002B5EH] .adr INTEGER 1685454913 .data ARRAY 256 OF INTEGER elements
Crystal
Crystal doesn't have an assert statement. the spec
module provides a testing DSL, but a simple assert can be created with a function or macro.
class AssertionError < Exception
end
def assert(predicate : Bool, msg = "The asserted condition was false")
raise AssertionError.new(msg) unless predicate
end
assert(12 == 42, "It appears that 12 doesn't equal 42")
D
import std.exception: enforce;
int foo(in bool condition) pure nothrow
in {
// Assertions are used in contract programming.
assert(condition);
} out(result) {
assert(result > 0);
} body {
if (condition)
return 42;
// assert(false) is never stripped from the code, it generates an
// error in debug builds, and it becomes a HALT instruction in
// -release mode.
//
// It's used as a mark by the D type system. If you remove this
// line the compiles gives an error:
//
// Error: function assertions.foo no return exp;
// or assert(0); at end of function
assert(false, "This can't happen.");
}
void main() pure {
int x = foo(true);
// A regular assertion, it throws an error.
// Use -release to disable it.
// It can be used in nothrow functions.
assert(x == 42, "x is not 42");
// This throws an exception and it can't be disabled.
// There are some different versions of this lazy function.
enforce(x == 42, "x is not 42");
}
Dart
Assert
main() {
var i = 42;
assert( i == 42 );
}
Expect
Testing assertions can be done using the test and expect functions in the test package
import 'package:test/test.dart';
main() {
int i=42;
int j=41;
test('i equals 42?', (){
expect( i, equals(42) );
});
test('j equals 42?', (){
expect( j, equals(42) );
});
}
Delphi
Assert(a = 42);
If an assertion fails, EAssertionFailed exception is raised.
The generation of assertion code can be disabled by compiler directive
{$ASSERTIONS OFF}
Here is a simple console demo app which raises and handles assertion exception:
program TestAssert;
{$APPTYPE CONSOLE}
{.$ASSERTIONS OFF} // remove '.' to disable assertions
uses
SysUtils;
var
a: Integer;
begin
try
Assert(a = 42);
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
Readln;
end.
DWScript
Simple assertion, with a custom (optional) message
Assert(a = 42, 'Not 42!');
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
procedure UniversalAnswer(var a : Integer);
require
a = 42;
begin
// code here
ensure
a = 42;
end;
Dyalect
Dyalect has a built-in "assert" function:
var x = 42
assert(42, x)
This function throws an exception if assertion fails.
E
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) # default message, "Required condition failed"
require(a == 42, "The Answer is Wrong.") # supplied message
require(a == 42, fn { `Off by ${a - 42}.` }) # computed only on failure
EchoLisp
(assert (integer? 42)) → #t ;; success returns true
;; error and return to top level if not true;
(assert (integer? 'quarante-deux))
⛔ error: assert : assertion failed : (#integer? 'quarante-deux)
;; assertion with message (optional)
(assert (integer? 'quarante-deux) "☝️ expression must evaluate to the integer 42")
💥 error: ☝️ expression must evaluate to the integer 42 : assertion failed : (#integer? 'quarante-deux)
ECL
ASSERT(a = 42,'A is not 42!',FAIL);
Ecstasy
Ecstasy assertions raise an exception on failure. The default assert
statement raises an IllegalState
, but there are a few varieties:
statement | exception class |
---|---|
assert |
IllegalState
|
assert:arg |
IllegalArgument
|
assert:bounds |
OutOfBounds
|
assert:TODO |
NotImplemented
|
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:
statement | exception class |
---|---|
assert:test |
Evaluate when in "test" mode, but never evaluate in production mode |
assert:once |
Evaluate the assertion only the first time it is encountered |
assert:rnd( n) |
Statistically sample, such that the assertion is evaluated 1 out of every n times that the assertion is encountered
|
This example will always evalaute (and fail) the assertion:
module test {
void run() {
Int x = 7;
assert x == 42;
}
}
Note that the text of the assertion expression and the relevant values are both included in the exception message:
- Output:
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)
Eiffel
version 2.4
There are many assertion types in Eiffel, one is the following:
File called main.e:
class MAIN
creation main
feature main is
local
test: TEST;
do
create test;
io.read_integer;
test.assert(io.last_integer);
end
end
Another file called test.e:
class TEST
feature assert(val: INTEGER) is
require
val = 42;
do
print("Thanks for the 42!%N");
end
end
Elixir
ExUnit.start
defmodule AssertionTest do
use ExUnit.Case
def return_5, do: 5
test "not equal" do
assert 42 == return_5
end
end
- Output:
1) test not equal (AssertionTest) test.exs:8 Assertion with == failed code: 42 == return_5 lhs: 42 rhs: 5 stacktrace: test.exs:9: (test) Finished in 0.1 seconds (0.1s on load, 0.01s on tests) 1 test, 1 failure Randomized with seed 869000
Emacs Lisp
(require 'cl-lib)
(let ((x 41))
(cl-assert (= x 42) t "This shouldn't happen"))
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.
1> N = 42.
42
2> N = 43.
** exception error: no match of right hand side value 43
3> N = 42.
42
4> 44 = N.
** 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 assert in other languages.
Euphoria
type fourty_two(integer i)
return i = 42
end type
fourty_two i
i = 41 -- type-check failure
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.
let test x =
assert (x = 42)
test 43
For additional information about assertions in .NET, see #C# and Visual Basic .NET
Factor
Throw an exception if the value on the top of the stack is not equal to 42:
USING: kernel ;
42 assert=
FBSL
One needs to DECLARE the asserter variable at the top of script.
This implementation evaluates the expression given to the function and displays a message if it evaluates to false.
#APPTYPE CONSOLE
DECLARE asserter
FUNCTION Assert(expression)
DIM cmd AS STRING = "DIM asserter AS INTEGER = (" & expression & ")"
EXECLINE(cmd, 1)
IF asserter = 0 THEN PRINT "Assertion: ", expression, " failed"
END FUNCTION
Assert("1<2")
Assert("1>2")
PAUSE
Output
Assertion: 1>2 failed Press any key to continue...
Forth
variable a
: assert a @ 42 <> throw ;
41 a ! assert
FreeBASIC
' FB 1.05.0 Win64
' requires compilation with -g switch
Dim a As Integer = 5
Assert(a = 6)
'The rest of the code will not be executed
Print a
Sleep
- Output:
assert.bas(5): assertion failed at __FB_MAINPROC__: a =6
GAP
# See section 7.5 of reference manual
# GAP has assertions levels. An assertion is tested if its level
# is less then the global level.
# Set global level
SetAssertionLevel(10);
a := 1;
Assert(20, a > 1, "a should be greater than one");
# nothing happens
a := 1;
Assert(4, a > 1, "a should be greater than one");
# error
# Show current global level
AssertionLevel();
# 10
Go
Assertions are a feature 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.
package main
func main() {
x := 43
if x != 42 {
panic(42)
}
}
Output:
panic: 42 panic PC=0x2b772d1a1048 runtime.panic+0xa7 /pool/go/src/pkg/runtime/proc.c:1032 runtime.panic(0x40e820, 0x2a) main.main+0x48 /pool/test.go:8 main.main() runtime.mainstart+0xf /pool/go/src/pkg/runtime/amd64/asm.s:77 runtime.mainstart() runtime.goexit /pool/go/src/pkg/runtime/proc.c:148 runtime.goexit()
Groovy
def checkTheAnswer = {
assert it == 42 : "This: " + it + " is not the answer!"
}
Test program:
println "before 42..."
checkTheAnswer(42)
println "before 'Hello Universe'..."
checkTheAnswer("Hello Universe")
Output:
before 42... before 'Hello Universe'... java.lang.AssertionError: This: Hello Universe is not the answer!. Expression: (it == 42). Values: it = Hello Universe at ConsoleScript80$_run_closure1.doCall(ConsoleScript80:2) at ConsoleScript80.run(ConsoleScript80:8)
Haskell
import Control.Exception
main = let a = someValue in
assert (a == 42) -- throws AssertionFailed when a is not 42
somethingElse -- what to return when a is 42
Icon and Unicon
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:
This produces the output:
10 42 is invalid value for 'a'
Changing the define to: $define DEBUG &fail
turns off the assertion checking.
J
assert n = 42
Java
In Java, the assert
keyword is used to place an assertive statement within the program.
A 'false' assertion will stop the program, as opposed to pausing, as with some other languages.
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.
Some JVM implementations will have assertions disabled by default, so you'll have to enable them at the command line, switch '-ea' or '-enableassertions'.
Inversely, to disable them, use '-da', or '-disableassertions'.
For more information see Oracle - Programming With Assertions.
The assert
syntax is as follows.
assert valueA == valueB;
It is essentially a boolean expression, which if not met, will throw an AssertionError
exception.
It is effectively shorthand for the following code.
if (valueA != valueB)
throw new AssertionError();
You can also specify a String
with the assertion, which will be used as the exception's detail-message, which is displayed with the stack-trace upon error.
assert valueA == valueB : "valueA is not 42";
Exception in thread "main" java.lang.AssertionError: valueA is not 42 at Example.main(Example.java:5)
You can also specify any other Object or primitive data type as a message.
If it's an object, the toString
method will be used as the message.
assert valueA == valueB : valueA;
JavaScript
function check() {
try {
if (isNaN(answer)) throw '$answer is not a number';
if (answer != 42) throw '$answer is not 42';
}
catch(err) {
console.log(err);
answer = 42;
}
finally { console.log(answer); }
}
console.count('try'); // 1
let answer;
check();
console.count('try'); // 2
answer = 'fourty two';
check();
console.count('try'); // 3
answer = 23;
check();
- Output:
try: 1 $answer is not a number 42
try: 2 $answer is not a number 42
try: 3 $answer is not 42 42
jq
Works with gojq, the Go implementation of jq
The assertion filters defined here are designed so that assertions intended for development or testing could be left in-place, possibly even in production code.
Highlights
- The input to every assertion filter is always passed through without alteration.
- If assertion checking is turned on, then an assertion violation
simply results in an error message being emitted on STDERR ("standard error").
- Assertions are only checked if the environment variable JQ_ASSERT
is set (see below for how to turn assertion checking on or off).
- Pinpointing the occurrence of an assertion violation by using $__loc__ is supported,
provided your implementation of jq includes this function.
The assertion checking filters defined here are as follows:
- assert(x)
- assert(x; msg)
- asserteq(x; y; msg)
where:
- msg determines the message that is printed as part of an assertion violation warning; it would typically be specified as a string or the $__loc__ object if your jq supports it.
JQ_ASSERT
Here is a table indicating how the JQ_ASSERT environment variable can be set or unset in various contexts:
SHELL SET UNSET sh bash (etc) export JQ_ASSERT=1 unset JQ_ASSERT fish set -x JQ_ASSERT 1 set -u JQ_ASSERT csh, tcsh setenv JQ_ASSERT 1 unsetenv JQ_ASSERT Windows/DOS SET JQ_ASSERT=1 set JQ_ASSERT= Windows: Start > Control Panel > System > Advanced > Environment Variables
See also the example below for how to set it on a per-invocation basis.
assert.jq
def assert(exp; $msg):
def m: $msg | if type == "string" then . else [.[]] | join(":") end;
if env.JQ_ASSERT then
(exp as $e | if $e then . else . as $in | "assertion violation @ \(m) => \($e)" | debug | $in end)
else . end;
def assert(exp):
if env.JQ_ASSERT then
(exp as $e | if $e then . else . as $in | "assertion violation: \($e)" | debug | $in end)
else . end;
def asserteq(x;y;$msg):
def m: $msg | if type == "string" then . else [.[]] | join(":") end;
def s: (if $msg then m + ": " else "" end) + "\(x) != \(y)";
if env.JQ_ASSERT then
if x == y then .
else . as $in | "assertion violation @ \(s)" | debug | $in
end
else . end;
Example
# File: example.jq
# This example assumes the availability of the $__loc__ function
# and that assert.jq is in the same directory as example.jq.
include "assert" {search: "."};
def test:
"This is an input"
| 0 as $x
| assert($x == 42; $__loc__),
asserteq($x; 42; $__loc__);
test
Invocation JQ_ASSERT=1 jq -n -f example.jq
In the output, the DEBUG line above appears on stderr.
- Output:
["DEBUG:","assertion violation @ <top-level>:16 => false"] "This is an input" ["DEBUG:","assertion violation @ <top-level>:17: 0 != 42"] "This is an input"
Julia
const x = 5
# @assert macro checks the supplied conditional expression, with the expression
# returned in the failed-assertion message
@assert x == 42
# ERROR: LoadError: AssertionError: x == 42
# Julia also has type assertions of the form, x::Type which can be appended to
# variable for type-checking at any point
x::String
# ERROR: LoadError: TypeError: in typeassert, expected String, got Int64
Kotlin
Kotlin supports Jva-style assertions. These need to be enabled using java's -ea option for an AssertionError
to be thrown when the condition is false. An assertion should generally never fire, and throws an Error
. Error
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.
fun main() {
val a = 42
assert(a == 43)
}
- Output:
Exception in thread "main" java.lang.AssertionError: Assertion failed at AssertKt.main(assert.kt:5)
A more Kotlin idiomatic approach to checks are the require
(and requireNotNull
) to check arguments, and the check
(and checkNotNull
), and error
to check state. The former is mostly meant for checking input, and will throw IllegalArgumentException
s, whereas the later is meant for state-checking, and will throw IllegalStateException
s
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
val fullName = "$firstName $lastName"
check(fullName.contains(" ")) { "fullname was expected to have a space...?" } // IllegalStateException
return fullName
}
Lasso
local(a) = 8
fail_if(
#a != 42,
error_code_runtimeAssertion,
error_msg_runtimeAssertion + ": #a is not 42"
)
- Output:
-9945 Runtime assertion: #a is not 42
Liberty BASIC
Liberty BASIC has no exceptions or user-defined error messages, but we could break program if condition is not met. We can even make it spell "AssertionFailed". In a way.
a=42
call assert a=42
print "passed"
a=41
call assert a=42
print "failed (we never get here)"
end
sub assert cond
if cond=0 then 'simulate error, mentioning "AssertionFailed"
AssertionFailed(-1)=0
end if
end sub
- Output:
passed
Stops with error message
- Output:
RuntimeError: Subscript out of range: -1, AssertionFailed()
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:
-- in a movie script
on assert (ok, message)
if not ok then
if not voidP(message) then _player.alert(message)
abort -- exits from current call stack, i.e. also from the caller function
end if
end
-- anywhere in the code
on test
x = 42
assert(x=42, "Assertion 'x=42' failed")
put "this shows up"
x = 23
assert(x=42, "Assertion 'x=42' failed")
put "this will never show up"
end
Lisaac
? { n = 42 };
Lua
a = 5
assert (a == 42)
assert (a == 42,'\''..a..'\' is not the answer to life, the universe, and everything')
M2000 Interpreter
M2000 use Error to produce error, Try variable {} and Try {} to capture errors, and return a number from a function when function called as module (zero means no error).
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
Module Assert {
\\ This is a global object named Rec
Global Group Rec {
Private:
document doc$="Error List at "+date$(today)+" "+time$(now)+{
}
Public:
lastfilename$="noname.err"
Module Error(a$) {
if a$="" then exit
.doc$<=" "+a$+{
}
flush error
}
Module Reset {
Clear .doc$
}
Module Display {
Report .doc$
}
Module SaveIt {
.lastfilename$<=replace$("/", "-","Err"+date$(today)+str$(now, "-nn-mm")+".err")
Save.Doc .doc$,.lastfilename$
}
}
Module Checkit {
Function Error1 (x) {
if x<10 then Print "Normal" : exit
=130 ' error code
}
Call Error1(5)
Try ok {
Call Error1(100)
}
If not Ok then Rec.Error Error$ : Flush Error
Test "breakpoint A" ' open Control form, show code as executed, press next or close it
Try {
Test
Report "Run this"
Error "Hello"
Report "Not run this"
}
Rec.Error Error$
Module Error1 (x) {
if x<10 then Print "Normal" : exit
Error "Big Error"
}
Try ok {
Error1 100
}
If Error then Rec.Error Error$
}
Checkit
Rec.Display
Rec.SaveIt
win "notepad.exe", dir$+Rec.lastfilename$
}
Assert
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.
// escape off // using escape off interpreter skip assert statements
x=random(0, 1)*10
try {
assert x=10
print x
}
Maple
(Taken from Lua, above.)
a := 5:
ASSERT( a = 42 );
ASSERT( a = 42, "a is not the answer to life, the universe, and everything" );
Mathematica / Wolfram Language
Assert[var===42]
MATLAB / Octave
assert(x == 42,'x = %d, not 42.',x);
Sample Output:
x = 3;
assert(x == 42,'Assertion Failed: x = %d, not 42.',x);
??? Assertion Failed: x = 3, not 42.
Metafont
Metafont has no really an assert built in, but it can easily created:
def assert(expr t) = if not (t): errmessage("assertion failed") fi enddef;
This assert
macro uses the errmessage
built in to show the "error". The
errmessage
gives the error message and asks the user what to do.
Usage example:
n := 41;
assert(n=42);
message "ok";
Output (failed assertion):
This is METAFONT, Version 2.71828 (Web2C 7.5.5) (./assert.mf ! assertion failed. <to be read again> ; l.4 assert(n=42); ?
Modula-3
ASSERT
is a pragma, that creates a run-time error if it returns FALSE
.
<*ASSERT a = 42*>
Assertions can be ignored in the compiler by using the -a
switch.
Nanoquery
a = 5
assert (a = 42)
Nemerle
A basic assertion uses the assert keyword:
assert (foo == 42, $"foo == $foo, not 42.")
Assertion violations throw an AssertionException with the line number where the assertion failed and the message provided as the second parameter to assert.
Nemerle also provides macros in the Nemerle.Assertions namespace to support preconditions, postconditions and class invariants:
using Nemerle.Assertions;
class SampleClass
{
public SomeMethod (input : list[int]) : int
requires input.Length > 0 // requires keyword indicates precondition,
// there can be more than one condition per method
{ ... }
public AnotherMethod (input : string) : list[char]
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 Nemerle.AssertionException's unless another Exception is specified using the otherwise keyword after the requires/ensures statement. For further details on design by contract macros, see here.
NGS
Assertions in NGS follow the general design of the language: return the original value, use patterns.
In the examples below, wherever 42 is a parameter by itself:
- better exception with expected and actual value is produced
- it is a pattern, numbers match themselves exactly, other patterns that would match: Int, 0..100, Any
a = 42
assert(a==42)
assert(a, 42)
assert(a==42, "Not 42!")
assert(a, 42, "Not 42!")
Nim
In Nim there are two main ways to check assertions.
var a = 42
assert(a == 42, "Not 42!")
This first kind of assertion may be disabled by compiling with --assertions:off or -d:danger.
var a = 42
doAssert(a == 42, "Not 42!")
This second kind of assertion cannot be disabled.
Nutt
module main
demand 5==42
end
Oberon-2
Oxford Oberon-2
MODULE Assertions;
VAR
a: INTEGER;
BEGIN
a := 40;
ASSERT(a = 42);
END Assertions.
Output:
Runtime error: assertion failed (0) on line 6 in module Assertions In procedure Assertions.%main called from MAIN
Objeck
If variable is not equal to 42 a stack trace is generated and the program is halts.
class Test {
function : Main(args : String[]) ~ Nil {
if(args->Size() = 1) {
a := args[0]->ToInt();
Runtime->Assert(a = 42);
};
}
}
Objective-C
For use within an Objective-C method:
NSAssert(a == 42, @"Error message");
If you want to use formatting arguments, you need to use the assertion macro corresponding to your number of formatting arguments:
NSAssert1(a == 42, @"a is not 42, a is actually %d", a); # has 1 formatting arg, so use NSAssert"1"
Within a regular C function you should use NSCAssert
or NSCAssertN
instead.
To turn off assertions, define the NS_BLOCK_ASSERTIONS macro.
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 *)
It is possible to compile with the parameter -noassert
then the compiler won't compile the assertion checks.
Oforth
In Oforth, assertions are handled as tests.
Assertions are checked only if oforth is launched using --a command line. Default value is to not check assertions.
If an assertion is ko (and if oforth is launched using --a), an exception is raised.
: testInteger(n, m)
assert: [ n isInteger ]
assert: [ n 42 == ]
System.Out "Assertions are ok, parameters are : " << n << ", " << m << cr ;
- Output:
testInteger(41, 43) [1:interpreter] ExRuntime : Assertion failed into <#testInteger> testInteger(42, 43) Assertions are ok, parameters are : 42, 43
Ol
(define i 24)
(assert i ===> 42)
; or
(assert (= i 42))
- Output:
Welcome to Otus Lisp 2.1-2486-481fd919 type ',help' to help, ',quit' to end session. > (define i 24) ;; Defined i > (assert i ===> 42) assertion error: i must be 42 > (assert (= i 42)) assertion error: (= i 42) is not a true
Oz
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).
declare
proc {PrintNumber N}
N=42 %% assert
{Show N}
end
in
{PrintNumber 42} %% ok
{PrintNumber 11} %% throws
Output:
%***************************** failure ************************** %** %** Tell: 11 = 42 %** %** Call Stack: %** procedure 'PrintNumber' in file "Oz<8>", line 3, column 0, PC = 18600220 %**--------------------------------------------------------------
PARI/GP
PARI can use any of the usual C methods for making assertions. GP has no built-in assertions.
#include <assert.h>
#include <pari/pari.h>
void
test()
{
GEN a;
// ... input or change a here
assert(equalis(a, 42)); /* Aborts program if a is not 42, unless the NDEBUG macro was defined */
}
More common is the use of pari_err_BUG
in such cases:
if (!equalis(a, 42)) pari_err_BUG("this_function_name (expected a = 42)");
Pascal
See Delphi
PascalABC.NET
Assert procedure works only in Debug mode. In Release all Assert calls are ignored. It is impossible to handle assertion exception.
begin
var a := 3;
Assert(a = 3);
Assert(a = 4, 'Bad assert!');
end.
Perl
While not exactly an assertion, a common Perl idiom is to use or die
to throw an exception when a certain statement is false.
print "Give me a number: ";
chomp(my $a = <>);
$a == 42 or die "Error message\n";
# Alternatives
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:
open my $fh, '<', 'file'
or die "Cannot open file: $!\n"; # $! contains the error message from the last error
It is not needed whith the "autodie" pragma:
use autodie;
open my $fh, '<', 'file'; # automatically throws an exception on failure
Some third-party modules provide other ways of using assertions in Perl:
use Carp::Assert;
assert($a == 42);
There is also a number of ways to test assertions in test suites, for example:
is $a, 42;
ok $a == 42;
cmp_ok $a, '==', 42, 'The answer should be 42';
# etc.
Phix
User defined types allow the value to be automatically tested whenever it changes, and can be disabled using the "without type_check" directive:
type int42(object i) return i=42 end type int42 i i = 41 -- type-check failure (desktop/Phix only)
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.
Note that, under "without type_check", the run-time reserves the right to continue to perform limited type checking, for example were the type declared as int42(integer i) then ensuring that i is an integer may allow subsequent optimisations to be applied, and therefore, despite the compiler directive, integer() could still be enforced even though "=42" would not.
You can also use constants to reduce code output on release versions:
global constant DEBUG = 0 -- (or any other identifier name can be used) global procedure check(integer flag, string msg) -- see also assert() below if DEBUG then if not flag then IupMessage("check failed",msg) -- or puts(1,msg) -- and/or crash(msg) -- crash/ex.err report, or trace(1) -- start debugging end if end if end function check(i=42,"i is not 42!!")
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 compiler may be possible, sometimes the calls may need "if DEBUG" around them. Also note that, as things stand, the constants 42 and "i is not 42!!" will be created in the executable file whatever DEBUG is set to, though again there is nothing to prevent the compiler from being enhanced to avoid emitting such unnecessary values, one day.
Lastly, I find the following trivial idioms to be spectacularly effective in Phix, the 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:
if i!=42 then ?9/0 end if if i!=42 then crash("i is not 42!!") end if assert(i=42,"i is not 42!!")
The assert statment is really just shorthand for the crash statement above it, except that the error message is optional (defaults to "assertion failure"). Again, if the application was run from Edita/Edix, on error it automatically jumps to the offending file and line.
PHP
<?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()
?>
Picat
Picat does not have a built-in assertion feature; a simple implementation is shown below. Note that predicates and functions must be handled differently:
- predicates: using
call/n
- functions: using
apply/n
The predicate/function that is tested but be "escaped" by $
in order to not be evaluated before the test.
go =>
%
% Test predicates
%
S = "ablewasiereisawelba",
assert("test1",$is_palindrome(S)),
assert_failure("test2",$not is_palindrome(S)),
assert("test3",$member(1,1..10)),
assert_failure("test4",$member(1,1..10)), % bad test
nl,
%
% Test functions
%
assert("test5",$2+2,4),
assert_failure("test6",$2+2, 5),
assert("test7",$to_lowercase("PICAT"),"picat"),
assert_failure("test8",$sort([3,2,1]),[1,3,2]),
nl.
is_palindrome(S) =>
S == S.reverse().
% Test a predicate with call/1
assert(Name, A) =>
println(Name ++ ": " ++ cond(call(A), "ok", "not ok")).
assert_failure(Name, A) =>
println(Name ++ ": " ++ cond(not call(A), "ok", "not ok")).
% Test a function with apply/1
assert(Name, A, Expected) =>
println(Name ++ ": " ++ cond(apply(A) == Expected, "ok", "not ok")).
assert_failure(Name, A, Expected) =>
println(Name ++ ": " ++ cond(apply(A) != Expected , "ok", "not ok")).
- Output:
test1: ok test2: ok test3: ok test4: not ok test5: ok test6: ok test7: ok test8: ok
PicoLisp
The '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:
(let N 41
(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:
(let N 41
(unless (= N 42) (! setq N 42)) ) # '!' is a breakpoint
(setq N 42) # Manually fix the value
! # Hit ENTER to leave the breakpoint
-> 42
PL/I
/* PL/I does not have an assert function as such, */
/* but it is something that can be implemented in */
/* any of several ways. A straight-forward way */
/* raises a user-defined interrupt. */
on condition (assert_failure) snap
put skip list ('Assert failure');
....
if a ^= b then signal condition(assert_failure);
/* Another way is to use the preprocessor, thus: */
%assert: procedure (a, b) returns (character);
return ('if ' || a || '^=' || b ||
' then signal condition(assert_failure);');
%end assert;
%activate assert;
assert(a, 42);
Prolog
test(A):-
assertion(A==42).
PureBasic
PureBasic does not have a native function for assertion, but allows for the definition of one.
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.
Macro Assert(TEST,MSG="Assert: ")
CompilerIf #PB_Compiler_Debugger
If Not (TEST)
Debug MSG+" Line="+Str(#PB_Compiler_Line)+" in "+#PB_Compiler_File
CallDebugger
EndIf
CompilerEndIf
EndMacro
A implementation as defined above could be;
A=42
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.
Python
a = 5
#...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 -O (optimizations) flag.
QB64
$ASSERTS:CONSOLE
DO
a = INT(RND * 10)
b$ = myFunc$(a)
PRINT a, , b$
_LIMIT 3
LOOP UNTIL _KEYHIT
FUNCTION myFunc$ (value AS SINGLE)
_ASSERT value > 0, "Value cannot be zero"
_ASSERT value <= 10, "Value cannot exceed 10"
IF value > 1 THEN plural$ = "s"
myFunc$ = STRING$(value, "*") + STR$(value) + " star" + plural$ + " :-)"
END FUNCTION
R
stopifnot(a==42)
Racket
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.
#lang racket
(define/contract x
(=/c 42) ; make sure x = 42
42)
(define/contract f
(-> number? (or/c 'yes 'no)) ; function contract
(lambda (x)
(if (= 42 x) 'yes 'no)))
(f 42) ; succeeds
(f "foo") ; contract error!
If typical assertion checking (i.e. error unless some boolean condition holds) is needed, that is also possible:
#lang racket
(define x 80)
(unless (= x 42)
(error "a is not 42")) ; will error
Raku
(formerly Perl 6)
my $a = (1..100).pick;
$a == 42 or die '$a ain\'t 42';
REXX
version 1
/* REXX ***************************************************************
* There's no assert feature in Rexx. That's how I'd implement it
* 10.08.2012 Walter Pachl
**********************************************************************/
x.=42
x.2=11
Do i=1 By 1
Call assert x.i,42
End
Exit
assert:
Parse Arg assert_have,assert_should_have
If assert_have\==assert_should_have Then Do
Say 'Assertion fails in line' sigl
Say 'expected:' assert_should_have
Say ' found:' assert_have
Say sourceline(sigl)
Say 'Look around'
Trace ?R
Nop
Signal Syntax
End
Return
Syntax: Say 'program terminated'
Output:
Assertion fails in line 8 expected: 42 found: 11 Call assert x.i,42 Look around Here I enter Say i 2 and then I press just enter program terminated
version 2
Programming note: this simple version will work better when the ASSERT be on one line,
and be without other REXX statements.
The clauses don't require parentheses, but are used here for clarity.
The ASSERT function could be programmed to exit as one of many
possible actions. Here, it just returns to the next REXX statement after the
call assert.
/*REXX program implements a simple ASSERT function; the expression can be compound. */
a = 1 /*assign a value to the A variable.*/
b = -2 /* " " " " " B " */
gee = 7.00 /* " " " " " GEE " */
zee = 26 /* " " " " " ZEE " */
call assert (a = 1)
call assert (b > 0)
call assert (gee = 7)
call assert (zee = a & zee>b)
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
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
- output when using the internal defaults:
===== ASSERT failure in REXX line 8, the statement is: ===== call assert (b > 0) ===== ASSERT failure in REXX line 10, the statement is: ===== call assert (zee = a & zee>b)
Ring
x = 42
assert( x = 42 )
assert( x = 100 )
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
if (a != 42)
{
stop("a is not 42 as expected, therefore I stop until this issue is resolved!");
}
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
- Output:
1: "Not good"
Ruby
This uses test/unit from the standard library.
require "test/unit/assertions"
include Test::Unit::Assertions
n = 5
begin
assert_equal(42, n)
rescue Exception => e
# Ruby 1.8: e is a Test::Unit::AssertionFailedError
# Ruby 1.9: e is a MiniTest::Assertion
puts e
end
Output:
<42> expected but was <5>.
Rust
let x = 42;
assert!(x == 42);
assert_eq!(x, 42);
Sather
class MAIN is
main is
i ::= 41;
assert i = 42; -- fatal
-- ...
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. here).
Scala
These two are the same thing, and are tagged @elidable(ASSERTION)
:
assert(a == 42)
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)
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 assert
, which, as explained, gets tagged.
println(a.ensuring(a == 42))
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"))
Scheme
(let ((x 42))
(assert (and (integer? x) (= x 42))))
SETL
assert( n = 42 );
Sidef
var num = pick(0..100);
assert_eq(num, 42); # dies when "num" is not 42
- Output:
assert_eq: 26 == 42 is false at assertions.sf line 2.
Slate
load: 'src/lib/assert.slate'.
define: #n -> 7.
assert: n = 42 &description: 'That is not the Answer.'.
raises an AssertionFailed condition (an Error).
Smalltalk
foo := 41.
...
self assert: (foo == 42).
In TestCase and subclasses, a number of check methods are inherited; among them:
self assert: (... somethingMustEvaluateToTrue.. )
self should:[ some code ] raise: someException "ensures that an exception is raised
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):
self assert: (... somethingMustEvaluateToTrue.. ) "implemented in Object"
the implementation in Object raises an AssertionFailedError exception, which usually opens a debugger when in the IDE, but can be caught in deployed apps.
SPARK
Works with SPARK GPL 2010
Assertions are analysed statically, before compilation or execution. They can appear in various places:
- inline in the code, either
-# check X = 42;
- or
-# assert X = 42;
- as a precondition on an operation:
procedure P (X : in out Integer);
--# derives X from *;
--# pre X = 42;
- or as a postcondition on an operation:
procedure P (X : in out Integer);
--# derives X from *;
--# post X = 42;
Example:
X := 7;
--# check X = 42;
produces the following output:
H1: true . -> C1: false .
which is an unprovable theorem that tells you that there is a guaranteed failure.
Standard ML
Using exceptions:
fun assert cond =
if cond then () else raise Fail "assert"
val () = assert (x = 42)
Stata
Assertions in Stata are limited to checking a property on the observations of a dataset. See assert in Stata help.
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:
assert x<y if z>0
There is another command, 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:
confirm file titanium.dta
If the file does not exist, an error is thrown with return code 601.
It's also possible to use 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:
if (`n'==42) error 3
* Will print "no dataset in use"
To print a more sensible message, one would do instead:
if (`n'==42) {
display as error "The correct answer is not 42."
exit 54
}
Then, if capture is used to trap the error, the return code (here 54) can be retrieved in _rc.
Swift
var a = 5
//...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.
Tcl
package require control
set x 5
control::assert {$x == 42}
Produces the output:
assertion failed: $x == 42
UNIX Shell
Assertions are not builtin commands, but we can add a function easily.
assert() {
if test ! $1; then
[[ $2 ]] && echo "$2" >&2
exit 1
fi
}
x=42
assert "$x -eq 42" "that's not the answer"
((x--))
assert "$x -eq 42" "that's not the answer"
echo "won't get here"
Vala
int a = 42;
int b = 33;
assert (a == 42);
assert (b == 42); // will break the program with "assertion failed" error
VBA
Sub test()
Dim a As Integer
a = 41
Debug.Assert a = 42
End Sub
- Output:
When run in the development area executing halts and highlights with yellow background the debug.assert line.
VBScript
Definition
sub Assert( boolExpr, strOnFail )
if not boolExpr then
Err.Raise vbObjectError + 99999, , strOnFail
end if
end sub
Invocation
dim i
i = 43
Assert i=42, "There's got to be more to life than this!"
Output
>cscript "C:\foo\assert.vbs"
C:\foo\assert.vbs(3, 3) (null): There's got to be more to life than this!
Visual Basic
VB's Assert
only fires when run from within the IDE. When compiled, all Debug
lines are ignored.
Debug.Assert i = 42
Visual Basic .NET
See #C# and Visual Basic .NET.
V (Vlang)
fn main(){
x := 43
assert x == 43 // Fine
assert x > 42 // Fine
assert x == 42 // Fails
}
- Output:
../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 ???
Wren
Wren does not have assertions as such though we can write something similar.
var assertEnabled = true
var assert = Fn.new { |cond|
if (assertEnabled && !cond) Fiber.abort("Assertion failure")
}
var x = 42
assert.call(x == 42) // fine
assertEnabled = false
assert.call(x > 42) // no error
assertEnabled = true
assert.call(x > 42) // error
- Output:
$ wren assertion.wren Assertion failure [./assertion line 4] in new(_) block argument [./assertion line 12] in (script)
The above module also provides limited support for assertions.
import "./debug" for Debug
var x = 42
Debug.assert("x == 42", 4, x == 42) // fine
Debug.off
Debug.assert("x > 42", 6, x > 42) // no error
Debug.on
Debug.assert("x > 42", 8, x > 42) // error
- Output:
ASSERTION on line 8 labelled 'x > 42' failed. Aborting fiber. Assertion failure. [./debug line 100] in assert(_,_,_) [./assert line 8] in (script)
XPL0
XPL0 does not have an assert command. The equivalent is usually synthesized something like this.
proc Fatal(Str); \Display error message and terminate program
char Str;
[\return; uncomment this if "assertions" are to be disabled
SetVid(3); \set normal text display if program uses graphics
Text(0, Str); \display error message
ChOut(0, 7); \sound the bell
exit 1; \terminate the program; pass optional error code to DOS
];
if X#42 then Fatal("X#42");
Yabasic
sub assert(a)
if not a then
error "Assertion failed"
end if
end sub
assert(myVar = 42)
Zig
const assert = @import("std").debug.assert;
pub fn main() void {
const n: i64 = 43;
assert(n == 42); // On failure, an `unreachable` is reached
}
Zig's assert gives a stack trace for debugging on failure.
Z80 Assembly
There is no hardware support for error handling, but the programmer can do this the same way they would create any other if
statement:
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
zkl
n:=42; (n==42) or throw(Exception.AssertionError);
n=41; (n==42) or throw(Exception.AssertionError("I wanted 42!"));
- Output:
Stack trace for VM#1 (): Cmd.__constructor addr:38 args(0) reg(1) startup.__constructor addr:2242 args(0) reg(1) ER startup.__constructor addr:2178 args(0) reg(22) Exception thrown: AssertionError(I wanted 42!)
zonnon
module Assertions;
var
a: integer;
begin
a := 40;
assert(a = 42,100)
end Assertions.
- Programming Tasks
- Basic language learning
- 11l
- 68000 Assembly
- Ada
- Aime
- ALGOL 68
- ALGOL W
- Apex
- Arturo
- AutoHotkey
- AWK
- Axe
- BASIC
- BaCon
- BASIC256
- BBC BASIC
- BQN
- Brat
- C
- C sharp
- Visual Basic .NET
- C++
- Clojure
- Common Lisp
- Component Pascal
- Crystal
- D
- Dart
- Delphi
- DWScript
- Dyalect
- E
- EchoLisp
- ECL
- Ecstasy
- Eiffel
- Elixir
- Emacs Lisp
- Erlang
- Euphoria
- F Sharp
- Factor
- FBSL
- Forth
- FreeBASIC
- GAP
- Go
- Groovy
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- Jq
- Julia
- Kotlin
- Lasso
- Liberty BASIC
- Lingo
- Lisaac
- Lua
- M2000 Interpreter
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- Metafont
- Modula-3
- Nanoquery
- Nemerle
- NGS
- Nim
- Nutt
- Oberon-2
- Objeck
- Objective-C
- OCaml
- Oforth
- Ol
- Oz
- PARI/GP
- Pascal
- PascalABC.NET
- Perl
- Phix
- PHP
- Picat
- PicoLisp
- PL/I
- Prolog
- PureBasic
- Python
- QB64
- R
- Racket
- Raku
- REXX
- Ring
- RLaB
- RPL
- Ruby
- Rust
- Sather
- Scala
- Scheme
- SETL
- Sidef
- Slate
- Smalltalk
- SPARK
- Standard ML
- Stata
- Swift
- Tcl
- Tcllib
- UNIX Shell
- Vala
- VBA
- VBScript
- Visual Basic
- V (Vlang)
- Wren
- Wren-debug
- XPL0
- Yabasic
- Zig
- Z80 Assembly
- Zkl
- Zonnon
- Gnuplot/Omit
- NSIS/Omit
- Pages with too many expensive parser function calls