Ring/Lessons/Eval() 和除錯
外觀
< Ring
在本節中,我們將學習
- 使用 Try/Catch/Done 處理錯誤
- Eval() 函式
- Raise() 函式
- Assert() 函式
語法
Try
Statements...
Catch
Statements...
DoneTry 塊中的語句將被執行,如果發生任何錯誤,則 catch 塊中的語句將被執行。
在 catch 塊中,我們可以使用變數 cCatchError 獲取錯誤訊息。
例子
Try
see 5/0
Catch
see "Catch!" + nl + cCatchError
Done輸出
Catch!
Error (R1) : Cann't divide by zero !
我們可以使用 Eval() 函式在執行時從字串執行程式碼。
語法
Eval(cCode)例子
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()輸出
5+2*5 = 15
1
2
3
4
5
6
7
8
9
10
message from test!
我們可以使用 Raise() 函式引發異常。
語法
Raise(cErrorMessage)該函式將顯示錯誤訊息,然後結束程式的執行。
我們可以使用 Try/Catch/Done 避免 raise() 函式生成的異常。
例子
nMode = 10if nMode < 0 or nMode > 5 raise("Error : nMode not in the range 1:4") ok
輸出
Line 4 Error : nMode not in the range 1:4
In raise in file tests\raise.ring例子
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輸出
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() 函式在執行程式碼之前測試條件。
如果測試失敗,程式將被終止,並顯示包含斷言條件的錯誤訊息。
語法
Assert( condition )例子
x = 10
assert( x = 10)
assert( x = 100 )輸出
Line 3 Assertion Failed!
In assert in file tests\assert.ring