捕获特定异常

异常处理

-- 错误是一个表:
-- 用字段 kind 区分不同的情形
local function check_data(data)
  if data == nil then
    error({kind = "is_nil"})
  end
  if #data == 0 then
    error({kind = "is_empty"})
  end
end

-- pcall 不能按类捕获:
-- 各种情形要在它之后再比较
local _, err = pcall(check_data, {})
local msg
if err.kind == "is_nil" then
  msg = "list is not specified"
elseif err.kind == "is_empty" then
  msg = "list is empty"
end
-- msg = list is empty

print("msg = " .. msg)