Assert

Assert[test]
represents the assertion that test is True. If assertions have been enabled, test is evaluated when the assertion is encountered. If test is not True, then an assertion failure is generated.

Assert[test, tag]
specifies a tag that will be used to identify the assertion if it fails.

DetailsDetails

  • Assertions are often placed in code to describe and check assumptions made by the programmer.
  • By default, assertions are disabled in an ordinary Mathematica session, but are enabled in the Mathematica debugger.
  • On[Assert] enables assertions in a Mathematica session, and causes a message to be generated whenever an assertion fails.
  • When Assert appears in a file, the name of the file and the line number at which it appears are by default automatically used as tags for the assertion.
  • In the Mathematica debugger, the failure of an assertion by default generates a breakpoint.
  • $AssertFunction gives a function to be applied to Assert[test, ...] when test does not evaluate to True.

ExamplesExamplesopen allclose all

Basic Examples (3)Basic Examples (3)

Define a function that contains an assertion depending on a temporary result as the computation runs:

In[1]:=
Click for copyable input

This does not test the assertion since assertions are not enabled:

In[2]:=
Click for copyable input
Out[2]=

When assertions are enabled with On, a message is produced:

In[3]:=
Click for copyable input
Out[3]=
In[4]:=
Click for copyable input

If you load a package that contains functions with assertions, the name of the package and line number is remembered:

In[2]:=
Click for copyable input

This shows how the line information and package name are stored in the Assert expression:

Now, if the assertion is triggered, the message tells you the name of the package and the line number where the assertion is located:

In[4]:=
Click for copyable input
Out[4]=

Disable assertions:

In[5]:=
Click for copyable input

You can change the behavior when an assertion fails by assigning to $AssertFunction. This function throws an exception when an assertion fails:

In[1]:=
Click for copyable input
In[2]:=
Click for copyable input

Here the exception thrown by the assertion function is caught:

In[3]:=
Click for copyable input
Out[3]=
In[4]:=
Click for copyable input
New in 8
New to Mathematica? Find your learning path »
Have a question? Ask support »