[Lua] try catch實現


參考了https://blog.csdn.net/waruqi/article/details/53649634這里的代碼,但實際使用時還有些問題,修改后在此記錄一下。

 1 -- 異常捕獲
 2 function try(block)
 3     -- get the try function
 4     local try = block[1]
 5     assert(try)
 6 
 7     -- get catch and finally functions
 8     local funcs = block[2]
 9 
10     -- try to call it
11     local ok, errors = xpcall(try, debug.traceback)
12     if not ok then
13         -- run the catch function
14         if funcs and funcs.catch then
15             funcs.catch(errors)
16         end
17     end
18 
19     -- run the finally function
20     if funcs and funcs.finally then
21         funcs.finally(ok, errors)
22     end
23 
24     -- ok?
25     if ok then
26         return errors
27     end
28 end
29 
30 function test()
31 try
32     {
33         function ()
34             xxx()
35         end,
36         {
37             -- 發生異常后,被執行
38             catch = function (errors)
39                 print("LUA Exception : " .. errors)
40             end,
41 
42             finally = function (ok, errors)
43                 -- do sth.
44                 print("finally can work")
45             end
46         },
47     }
48 print("I can print normally!")
49 end
50 
51 test()
異常捕獲代碼+測試代碼

調用test()后,運行結果如下:

 

又改了一版,格式輸入看起來更容易理解,代碼如下:

 1 -- 異常捕獲
 2 function try1(block)
 3     local main = block.main
 4     local catch = block.catch
 5     local finally = block.finally
 6 
 7     assert(main)
 8 
 9     -- try to call it
10     local ok, errors = xpcall(main, debug.traceback)
11     if not ok then
12         -- run the catch function
13         if catch then
14             catch(errors)
15         end
16     end
17 
18     -- run the finally function
19     if finally then
20         finally(ok, errors)
21     end
22 
23     -- ok?
24     if ok then
25         return errors
26     end
27 end
28 
29 function test1()
30 try1{
31         main = function ()
32             xxx()
33         end,
34         catch = function (errors)
35             print("catch : " .. errors)
36         end,
37         finally = function (ok, errors)
38             print("finally : " .. tostring(ok))
39         end,
40     }
41 print("I can print normally!")
42 end
43 
44 test1()
新版try-catch

打印結果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM