Lua Error Handling
Error handling during program execution is necessary. Unexpected errors can occur during file operations, data transfer, and web service calls. If you don't pay attention to error message handling, it can lead to information leaks, program failures, and other situations.
Error handling is needed in any programming language. Error types include:
- Syntax errors
- Runtime errors
Syntax errors
Syntax errors are usually caused by improper use of program components (such as operators and expressions). A simple example is as follows:
-- test.lua file
a == 2
The execution result of the code above is:
lua: test.lua:2: syntax error near '=='
As you can see, there is a syntax error above. A single "=" is different from two "==". One "=" is an assignment expression, while two "==" is a comparison operation.
Another example:
Example
for
a
=
1
,
10
(
a
)
end
Executing the above program produces the following error:
lua: test2.lua:2: 'do' expected near 'print'
Syntax errors are simpler than program runtime errors. Runtime errors cannot pinpoint the specific error, while syntax errors can be resolved quickly. For example, in the above case we just need to add do under the for statement:
Example
for
a
=
1
,
10
do
(
a
)
end
Runtime errors
A runtime error means the program executes normally but outputs an error message. In the following example, due to incorrect parameter input, the program reports an error during execution:
function add(a,b)
return a+b
end
add(10)
When we compile and run the following code, compilation succeeds, but the following error occurs at runtime:
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 calling a function in lua, even if the argument list and parameter list don't match, the call still succeeds. Extra arguments are discarded, and missing arguments are filled with nil.
The above error occurs because after parameter b is filled with nil, nil participates in the + operation.
If add inside the function is not "return a+b" but instead "print(a,b)" , the result will become "10 nil" no error will be reported.
Error handling
We can use two functions, assert and error, to handle errors. Example:
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
)
Executing the above program produces the following error:
lua: test.lua:3: b 不是一个数字
stack traceback:
[C]: in function 'assert'
test.lua:3: in local 'add'
test.lua:6: in main chunk
[C]: in ?
In the example, assert first checks the first argument. If there is no problem, assert does nothing; otherwise, assert throws the second argument as the error message.
The error function
Syntax format:
error (message [, level])
Function: terminates the currently executing function and returns the content of message as the error information (the error function never returns)
Normally, error appends some error location information to the beginning of message.
The Level parameter indicates the location where the error is obtained:
- Level=1 [default]: the location where error is called (file + line number)
- Level=2: indicates which function called the error function
- Level=0: no error location information is added
pcall, xpcall, and debug
To handle errors in Lua, you can use the function pcall (protected call) to wrap the code that needs to be executed.
pcall receives a function and the arguments to pass to it, and executes them. Execution result: with error or without error; returns true or false, errorinfo.
The syntax format is as follows
if pcall(function_name, ….) then
-- 没有错误
else
-- Some errors
end
Simple example:
Example
=
pcall
(
function
(
i
)
(
i
)
end
,
33
)
33
true
=
pcall
(
function
(
i
)
(
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 argument in a "protected mode", so pcall can capture any errors during function execution.
Usually when an error occurs, you want more debugging information, not just the location where the error occurred. But when pcall returns, it has already destroyed part of the call stack.
Lua provides the xpcall function, which takes a second argument, an error handling function. When an error occurs, Lua calls the error handling function before the call stack is unwound (unwind), so you can use the debug library in this function to get additional information about the error.
The debug library provides two common error handling functions:- debug.debug: provides a Lua prompt that lets the user check the cause of the error
- debug.traceback: builds an extended error message based on the call stack
>=xpcall(function(i) print(i) error('error..') end, function() print(debug.traceback()) end, 33)
33
stack traceback:
stdin:1: in function
[C]: in function 'error'
stdin:1: in function
[C]: in function 'xpcall'
stdin:1: in main chunk
[C]: in ?
false nil
xpcall usage example 2:
Example
n = n/nil
end
function myerrorhandler( err )
print( "ERROR:", err )
end
status = xpcall( myfunction, myerrorhandler )
print( status)
Executing the above program produces the following error:
ERROR: test2.lua:2: attempt to perform arithmetic on global 'n' (a nil value) false