pcall and xpcall
https://www.tutorialspoint.com/lua/lua_error_handling.htm
In Lua programming, in order to avoid throwing these errors and handling errors, we need to use the functions pcall or xpcall.
The pcall (f, arg1, ...) function calls the requested function in protected mode. If some error occurs in function f, it does not throw an error. It just returns the status of error. A simple example using pcall is shown below.
function myfunction () n = n/nil end if pcall(myfunction) then print("Success") else print("Failure") end
When we run the above program, we will get the following output.
Failure
The xpcall (f, err) function calls the requested function and also sets the error handler. Any error inside f is not propagated; instead, xpcall catches the error, calls the err function with the original error object, and returns a status code.
A simple example for xpcall is shown below.
function myfunction () n = n/nil end function myerrorhandler( err ) print( "ERROR:", err ) end status = xpcall( myfunction, myerrorhandler ) print( status)
When we run the above program, we will get the following output.
ERROR: test2.lua:2: attempt to perform arithmetic on global 'n' (a nil value) false
As a programmer, it is most important to ensure that you take care of proper error handling in the programs you write. Using error handling can ensure that unexpected conditions beyond the boundary conditions are handled without disturbing the user of the program.