Skip to content

Errors and Assertions

Jean Dubois edited this page Jun 1, 2023 · 2 revisions

Assertion

You can assert anything you want anywhere in your code.

Usage

  • assert condition
  • assert condition, 'errmsg'

Behavior

If the condition is true, it does nothing.

If the condition is false, it stops completely the program. If there is a error message, stops with the message.

Example

def sqrt(number)
    assert is_num(number)
    assert number >= 0, "number must be positive"

    import math
    return math_sqrt(number)
end

Note : here math_sqrt is already crashing if the number is not a number of is negative.

Output

nougaro> sqrt(16)
4.0
nougaro> sqrt("abc")
Traceback (more recent call last) :
 In file <stdin>, line 1, in <program> :
 In file tests.noug, line 2, in sqrt :

 	
	    assert is_num(number)
	           ^^^^^^^^^^^^^
 AssertionError
nougaro> sqrt(-16)
Traceback (more recent call last) :
 In file <stdin>, line 1, in <program> :
 In file tests.noug, line 3, in sqrt :

 	
	    assert number >= 0, "number must be positive"
	           ^^^^^^^^^^^
 AssertionError: number must be positive
nougaro> 
Clone this wiki locally