Assertion Failed
rascal-0.41.2
Synopsis
An assertion in the Rascal code is false.
Function
data RuntimeException = AssertionFailed(str label);
Description
An Assert statement can be used to check assumptions during the execution of a Rascal program. This error is generated if an assertion is not true.
Remedies:
- Modify your code to make the assertion true.
- Modify your assertion to reflect the current behaviour of your code.
- Catch the
AssertionFailedyourself, see try catch.
Examples
A false assertion gives an error:
rascal>assert 3 > 4;
|prompt:///|(0,13,<1,0>,<1,13>): AssertionFailed()
at $(|main:///_dollar_|)
Define a function that only increments positive integers:
rascal>int incrPositive(int n) {
|1 >>>> assert n > 0: "n should be greater than 0"; return n + 1;
|2 >>>>}
int (int): function(|prompt:///|(0,89,<1,0>,<3,1>))
Calling it with a positive integer is fine:
rascal>incrPositive(3);
int: 4
But a negative argument gives an error:
rascal>incrPositive(-3);
|prompt:///|(43,28,<2,16>,<2,44>): AssertionFailed("n should be greater than 0")
at incrPositive(|prompt:///|(0,89,<1,0>,<3,1>))
at $(|prompt:///|(0,17,<1,0>,<1,17>))
We can also catch the AssertionFailed error. First import the Rascal exceptions (which are also included in Prelude)
and IO:
rascal>import Exception;
ok
rascal>import IO;
ok
rascal>try
|1 >>>> println(incrPositive(-3));
|2 >>>>catch AssertionFailed(str msg):
|3 >>>> println("incrPositive: <msg>");
incrPositive: n should be greater than 0
ok
Benefits
- Enables the precise expression of assumptions in your code.
- Asserts are actually executed when the compiler option
enableAssertsis set to true (by default set tofalse). - In the RascalShell,
enableAssertsis always true.