Lua error handling
Error handling is necessary when the program is running, and unexpected errors will occur in the process of file operation, data transfer and web service call. If we do not pay attention to the handling of error messages, it will lead to information disclosure, the program can not run and so on.
Error handling is required in any programming language. The types of errors are:
Grammatical error
Running error
Grammatical error
Syntax errors are usually caused by improper use of components of the program, such as operators and expressions. A simple example is as follows:
-- test.lua file
a == 2
The result of the above code execution is:
lua: test.lua:2: syntax error near '=='
As you can see, there are grammatical errors above, and there is a difference between one “=” sign and two “=” signs. One “=” is an assignment expression and two “=” are comparison operations.
Another example:
Example
for a= 1,10
print(a)
end
The following error occurs when executing the above procedure:
lua: test2.lua:2: 'do' expected near 'print'
Syntax errors are simpler than program running errors, which can not locate specific errors, but syntax errors can be solved quickly, such as the above example. for
add under the statement do
:
Example
for a= 1,10
do
print(a)
end
Running error
The running error means that the program can be executed normally, but the error message will be output. The following example caused an error in the execution of the program due to an error in the input of parameters:
function add(a,b)
return a+b
end
add(10)
When we compile and run the following code, the compilation can be successful, but the following error occurs at run time:
lua: test2.lua:2: attempt to perform arithmetic on local 'b' (a nil value)
stack traceback:
test2.lua:2: in function 'add'
test2.lua:5: in main chunk
[C]: ?
When a lua
function is called in, it can be called successfully even if the argument list is inconsistent with the formal parameter list, the extra parameters will be discarded and the missing parameters will be added to nil
.
The above error message is due to the addition of parameter b nil
after nil
participated in the + operation.
If add
not within the function "return a+b"
but "print(a,b)"
if so, the result will be "10 nil"
it won’t be wrong.
Error handling
We can use two functions: assert
and error
to deal with errors. Examples are as follows:
Example
local function add(a,b)
assert(type(a) == "number", "a is not a number")
assert(type(b) == "number", "b is not a number")
return a+b
end
add(10)
The following error occurs when executing the above procedure:
lua: test.lua:3: b is not a number
stack traceback:
[C]: in function 'assert'
test.lua:3: in local 'add'
test.lua:6: in main chunk
[C]: in ?
In the instance assert
first check the first parameter, if there is no problem assert
. Don’t do anything; otherwise assert
thrown with thesecond parameter as an error message.
Error function
Syntax format:
error (message [, level])
Function: terminates the function being executed and returns message
asan error message error
the function will never return)
Under normal circumstances error
will attach some information about thewrong location to message
head.
Level
parameter indicates where to get the error:
Level=1
[default]: is the location (file+line number) for callingerror
Level=2
indicate which callerror
the function of the functionLevel=0
:Do not add error location information
Pcall and xpcall, debug
To handle errors in Lua, you can use functions pcall
(protected call) to wrap the code that needs to be executed.
pcall
receives a function and the parameters to be passed to the latter, and executes it. The execution result is either error free or error free; Return values of true
or false
, errorinfo
.
The syntax format is as follows
if pcall(function_name, ….) then
-- freedom from error
else
-- Some errors
end
Simple example:
Example
> =pcall(function(i) print(i) end, 33)
33
true
> =pcall(function(i) print(i) error('error..') end, 33)
33
false stdin:1: error..
> function f() return false,2 end
> if f() then print '1' else print '0' end
0
Pcall calls the first parameter in a “protected mode”, so pcall
you can catch any error in the execution of the function.
Usually when an error occurs, you want to get more debugging information, not just where the error occurred. But when the pcall returns, it has destroyed some of the contents of the call to notify.
Lua provides the xpcall function, and xpcall takes the second argument– an error handler. When an error occurs, Lua calls the error handler before calling unwind, so you can use the debug library in this function to get additional information about the error.
debug
the library provides two general error handling functions:
debug.debug
:Provide a Lua prompt for users to check the cause of the errordebug.traceback
:Build an extended error message based on the call to notify
>=xpcall(function(i) print(i) error('error..') end, function() print(debug.traceback()) end, 33)
33
stack traceback:
stdin:1: in function <stdin:1>
[C]: in function 'error'
stdin:1: in function <stdin:1>
[C]: in function 'xpcall'
stdin:1: in main chunk
[C]: in ?
false nil
xpcall
use example 2:
Example
function myfunction ()
n = n/nil
end
function myerrorhandler( err )
print( "ERROR:", err )
end
status = xpcall( myfunction, myerrorhandler )
print( status)
The following error occurs when executing the above procedure:
ERROR: test2.lua:2: attempt to perform arithmetic on global 'n' (a nil value)
false