捕获特定异常

异常处理

-- The error is a table: the field kind
-- tells one case from another
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 has no catch per class: the cases
-- are compared after it
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)