珍蜗蜗

不断向前

导航

[Lua] try catch实现

Posted on 2018-05-15 16:24  珍蜗蜗  阅读(2615)  评论(0编辑  收藏  举报

参考了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

打印结果如下: