When our Lua program encounters code or methods that require protection (even if the program is abnormal, it only throws exception information, rather than causing the program to crash ), lua provides us with two solutions. These two methods allow us to capture exceptions and therefore encapsulate our own trycatch function.
1. Call pcall
2. xpcall call
Similarities:If the program is normal, true is returned, and the returned value of the executed function is
Differences:
1. Different parameters have different pcall (fun) parameters. The parameter has only one called function xpcall (fun, errhandlefun). The parameter is called function, and the error function is processed.
2. Execution result pcall: When an error message is returned, the stack information for saving the error has been released. Xpcall: the error handler will be called before stack information is released (you can use the debug library to collect error information)
3. Return result pcall return nil, error message
Xpcall returns nil with no error message
Instance:
local fun=function ( ... )local a=1;print(a+1);return a+1;endtryCatch=function(fun)local ret,errMessage=pcall(fun);print("ret:" .. (ret and "true" or "false" ) .. " \nerrMessage:" .. (errMessage or "null"));endxTryCatchGetErrorInfo=function()print(debug.traceback());endxTryCatch=function(fun)local ret,errMessage=xpcall(fun,xTryCatchGetErrorInfo);print("ret:" .. (ret and "true" or "false" ) .. " \nerrMessage:" .. (errMessage or "null"));endprint("\n------A------\n")tryCatch(fun);print("\n------B------\n")xTryCatch(fun);print("\n------C------\n")
Execution result:
The second line of the annotation function fun is local A = 1; then the following result is printed:
Catch exceptions (trycatch encapsulation) in the Lua learning tutorial)