Catch exceptions (trycatch encapsulation) in the Lua learning tutorial)

Source: Internet
Author: User
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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.