4. 错误处理和异常
对大多数程序来说,不需要在Lua代码中进行错误处理,宿主程序本身会对错误进行相应处理。所有的Lua动作基本都是由宿主程序调用起来的,如果发生错误,Lua代码块只需要返回相应的err_code,宿主程序本身针对err_code做出相应的处理。在独立的Lua解析器中,出错的时候,也只是打印出相应的错误信息,然后继续提示用户继续进行运行其他的命令。
如果想要在Lua中对错误进行处理,那么必须用pcall (protected call)函数来封装代码。
假设我们运行一段lua代码,并捕获到运行过程中出现的错误。我们首先要做的就是封装这段代码,假设封装成函数foo :
function foo ()
<some code>
if unexpected_condition then error() end
<some code>
print(a[i]) -- potential error: 'a' may not be a table
<some code>
end
然后用pcall 去调用这个函数:
if pcall(foo) then
-- no errors while running 'foo'
<regular code>
else
-- 'foo' raised an error: take appropriate actions
<error-handling code>
end
上面的foo 函数也可以替换成匿名函数的。
pcall 会在protected mode下调用它的第一个参数,以便能够在函数运行过程中捕获到出现的错误。如果函数运行正常,没有错误产生,pcall 返回true + 函数的返回值;如果出现错误,pcall 返回false + err_msg。
err_msg不一定非得是string,任何传递给error 的值都会被pcall 返回,例如下面的示例:
local status, err = pcall(function () error({code=121}) end)
print(status, err.code, type(err))
运行结果如下:

5. 错误信息和堆栈
像上面说的,任何类型的值都可以作为err_msg,但是,通常err_msg还是string类型的,说明发生了什么错误。当遇到了内部错误(例如试图索引一个非table值),Lua负责产生err_msg;否则,err_msg就是传递给error 函数的值。另外,Lua总是在错误发生的地方添加一些位置信息, 如下示例:
local status, err = pcall(function () a = "a"+1 end)
print(err)

local status, err = pcall(function () error("my error") end)
print(err)

位置信息指明了filename和line number。
error 函数有一个额外的参数level, 说明如何获取错误发生的位置。level默认为1,返回error 函数被调用的位置; level 为2, 返回调用error 函数的函数被调用的位置; level 为0,不获取位置信息。对比下下面三段代码的的区别和执行结果就明白了。
function foo(str)
if type(str) ~= "string" then
error("string expected", 0) --level 0
end
print("foo success")
end
local status, err = pcall(foo(3))
print(err)
运行结果:

function foo(str)
if type(str) ~= "string" then
error("string expected", 1) --level 1
end
print("foo success")
end
local status, err = pcall(foo(3))
print(err)
运行结果:

function foo(str)
if type(str) ~= "string" then
error("string expected", 2) --level 2
end
print("foo success")
end
local status, err = pcall(foo(3))
print(err)
运行结果:

err_test03.lua, err_test04.lua是我code文件的名字而已,可能每个人起名字都不同的。注意一下level 1 和level 2的错误行号是不同的。通过这3个例子,很明白了吧。
通常情况下,在程序出错的时候,可能仅仅知道错误发生的位置是不够的。至少,还需要函数的调用堆栈吧。但是当pcall 函数返回的时候,堆栈信息已被部分破坏了。因此,为了获取堆栈信息,必须在pcall 返回之前就建立它。Lua为我们提供了xpcall 函数, 它比pcall 函数多一个参数 error handler function。 一旦发生错误,Lua在堆栈被损坏之前调用这个handler 函数,在handler 中,我们可以用debug 库来收集尽可能的有关错误的信息。两个常用的handler 函数是debug.debug 和 debug.traceback ;具体用法,后续会详细讨论。
