Lua错误处理
Lua 错误处理
为什么需要错误处理机制
在真实的系统中程序往往非常复杂,它们经常涉及到文件操作、数据库事务操作或网络服务调用等,这个时候错误处理就显得非常重要。不关注错误处理可能在处理诸如涉密或金融交易这些业务时造成重大的损失。
无论什么时候,程序开发都要求小心地做好错误处理工作。在 Lua 中错误可以被分为两类:
- 语法错误
- 运行时错误
语法错误
语法错误是由于不正确的使用各种程序语法造成的,比如错误的使用操作符或表达式。下面即是一个语法错误的例子:
1 | a == 2 |
for a= 1,10
print(a)
end
1 |
|
lua: test2.lua:2: ‘do’ expected near ‘print’
1 |
|
function add(a,b)
return a+b
end
add(10)
1 |
|
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]: ?
1 |
|
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)
1 |
|
lua: test2.lua:3: b is not a number
stack traceback:
[C]: in function ‘assert’
test2.lua:3: in function ‘add’
test2.lua:6: in main chunk
[C]: ?
1 |
|
function myfunction ()
n = n/nil
end
if pcall(myfunction) then
print(“Success”)
else
print(“Failure”)
end
1 |
|
Failure
1 |
|
function myfunction ()
n = n/nil
end
function myerrorhandler( err )
print( “ERROR:”, err )
end
status = xpcall( myfunction, myerrorhandler )
print( status)
1 |
|
ERROR: test2.lua:2: attempt to perform arithmetic on global ‘n’ (a nil value)
false
作为程序开发人员,在程序中正确合理地处理错误是非常重要的。正确地处理错误可以保证发生意外情况不会影响到程序用户的使用。