Lua语言学习之错误与异常

error and exception


程序健壮性的一个体现就是对异常和错误的处理。

     由于Lua是一种扩展语言,通常嵌入在应用程序中,因此在发生错误时它不能简单地奔溃或退出。

相反,只要发生了一个错误,Lua就应该结束当前程序块并返回应用程序。

1. error 函数

      Lua程序遇到不合法操作时都会引发一个错误,也可以显示地引发一个错误,通过调用 error 函数并

传入一个错误消息的参数。通常这个函数就是一种比较恰当的处理错误的方式。

一般形式是:

if not < condition > then error end

函数原型:error ( message [, level ]

Terminates the last protected function called and returns message as the error message. Function error never returns.

Usually, error adds some information about the error position at the beginning of the message. 

The level argument specifies how to get the error position. With level 1 (the default),

the error position is where the error function was called.

Level 2 points the error to where the function that called error was called; and so on. 

Passing a level 0 avoids the addition of error position information to the message.


2. assert 函数

Lua 提供了一个内建函数 assert 来完成 error 函数的组合:

print " enter a number : "

n = assert( io.read( " *number" ), " invalid input " )

assert 函数检查其第一个参数是否为 true,若为true,则简单地返回该参数,否则就引发一个错误。

它的第二个参数是一个可选的信息字符串。

Lua中有一个习惯:如果io.open失败,assert将抛出错误。
file = assert(io.open("no-file", "r"))
       --> stdin:1: no-file: No such file or directory
注意:io.open返回的第二个结果(错误信息)会作为assert的第二个参数。

3. 错误处理:pcall 函数

如果需要在 Lua 中处理错误,则必须使用函数 pcall 来包装需要执行的代码。

假定你想运行一段Lua代码,这段代码运行过程中可以捕捉所有的异常和错误。
第一步:将这段代码封装在一个函数内
function foo ()
    ...
    if unexpected_condition then error() end
    ...
    print(a[i])   -- potential error: `a' may not be a table
    ...
end
第二步:使用pcall调用这个函数
if pcall(foo) then
    -- no errors while running `foo'
    ...
else
    -- `foo' raised an error: take appropriate actions
    ...
end
当然也可以用匿名函数的方式调用pcall:
if pcall(function () ... end) then ...
else ...
pcall在保护模式(protected mode)下执行函数内容,同时捕获所有的异常和错误。

若一切正常,pcall返回true以及“被执行函数”的返回值;否则返回nil和错误信息。

错误信息不一定仅为字符串(下面的例子是一个table),传递给error的任何信息都会被pcall返回:
local status, err = pcall(function () error({code=121}) end)
print(err.code) --> 121
这种机制提供了强大的能力,足以应付Lua中的各种异常和错误情况。我们通过error抛出异常,

然后通过pcall捕获之。


4. 追溯:traceback

当错误发生的时候,我们常常希望了解详细的信息,而不仅是错误发生的位置。

若能了解到“错误发生时的栈信息”就好了,但pcall返回错误信息时,

已经释放了保存错误发生情况的栈信息。因此,若想得到tracebacks,我们必须在pcall返回以前获取。

Lua提供了xpcall来实现这个功能,xpcall接受两个参数:调用函数、错误处理函数。

当错误发生时,Lua会在栈释放以前调用错误处理函数,因此可以使用debug库收集错误相关信息。

有两个常用的debug处理函数:debug.debug和debug.traceback,前者给出Lua的提示符,

你可以自己动手察看错误发生时的情况;后者通过traceback创建更多的错误信息,

也是控制台解释器用来构建错误信息的函数。

你可以在任何时候调用debug.traceback获取当前运行的traceback信息:
print(debug.traceback())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值