Eval() and Debugging

In this chapter we are going to learn about

  • Error Handling using Try/Catch/Done

  • Eval() function

  • Raise() function

  • Assert() function

Try/Catch/Done

Syntax:

Try
        Statements...
Catch
        Statements...
Done

The statements in the Try block will be executed, if any error happens then the statements in the catch block will be executed.

Inside the catch block we can use the variable cCatchError to get the error message

Example:

Try
        see 5/0
Catch
        see "Catch!" + nl + cCatchError
Done

Output:

Catch!
Error (R1) : Can't divide by zero !

Eval() Function

We can execute code during the runtime from string using the Eval() function

Syntax:

Eval(cCode)

Example:

Eval("nOutput = 5+2*5 " )
See "5+2*5 = " + nOutput + nl
Eval("for x = 1 to 10 see x + nl next")
Eval("func test see 'message from test!' ")
test()

Output:

5+2*5 = 15
1
2
3
4
5
6
7
8
9
10
message from test!

We can use the Return command to return a value

Example:

see Eval("return 5*5")

Output:

25

Raise() Function

We can raise an exception using the Raise() function

Syntax:

Raise(cErrorMessage)

The function will display the error message then end the execution of the program.

We can use Try/Catch/Done to avoid exceptions generated by raise() function.

Example:

nMode = 10

if nMode < 0 or nMode > 5
        raise("Error : nMode not in the range 1:4")
ok

Output:

Line 4 Error : nMode not in the range 1:4
In raise in file tests\raise.ring

Example:

try
        testmode(6)
catch
        see "avoid raise!"
done

testmode(-1)

func testmode nMode

        if nMode < 0 or nMode > 5
                raise("Error : nMode not in the range 1:4")
        ok

Output:

avoid raise!
Line 12 Error : nMode not in the range 1:4
In raise In function testmode() in file tests\raise2.ring
called from line 7  in file tests\raise2.ring

Assert() Function

We can use the Assert() function to test conditions before executing the code

If the test fail the program will be terminated with an error message contains the assert condition.

Syntax:

Assert( condition )

Example:

x = 10
assert( x = 10)
assert( x = 100 )

Output:

Line 3 Assertion Failed!
In assert in file tests\assert.ring