> status, err = pcall( function() error({code = 121}) end )
> print(status)
false
> print(err)
table: 0x22033b0
> print(err.code)
121
如果函数被正常调用, 返回正常的结果
> status, err,a,b,c = pcall( function(...) return ... end, 1, 2, 3 )
> print(status,err,a,b,c)
true 1 2 3 nil
> p = function(...) return ... end
> status, err,x,y,z = pcall( p, 1,2,3 )
> print(status,err,x,y,z)
true 1 2 3 nil
function foo ()
...
if unexpected_condition then error() end
...
print(a[i]) -- potential error: `a' may not be a table
...
end
Then, you call foo with pcall:
if pcall(foo) then
-- no errors while running `foo'
...
else
-- `foo' raised an error: take appropriate actions
...
end
[参考]
pcall (f [, arg1, ···])
Calls function f
with the given arguments in protected mode. This means that any error inside f
is not propagated; instead, pcall
catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall
also returns all results from the call, after this first result. In case of any error,pcall
returns false plus the error message.
error (message [, level])
Terminates the last protected function called and returnsmessage
as the error message. Function
error
never returns.
Usually, error
adds some information about the error position at the beginning of the message, if the message is a string. 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.