定义异常类型

异常处理

-- 错误类:其错误的元表
local SimpleError = {kind = "SimpleError"}
SimpleError.__index = SimpleError

function SimpleError.new(message)
  return setmetatable({message = message},
                      SimpleError)
end

-- 若不处理,这个错误会终止脚本
local _, err = pcall(function()
  error(SimpleError.new("Oops!"))
end)

-- type:错误是表,而不是字符串
local err_type = type(err)
-- err_type = table

-- getmetatable 给出类
local is_simple = getmetatable(err) == SimpleError
-- is_simple = true

-- kind 在类中找到
local err_kind = err.kind
-- err_kind = SimpleError
local err_message = err.message
-- err_message = Oops!

-- 文本错误是另一种类型
local _, text_err = pcall(error, "Oops!", 0)
local text_type = type(text_err)
-- text_type = string

print("err_type = " .. err_type)
print("is_simple = " .. tostring(is_simple))
print("err_kind = " .. err_kind)
print("err_message = " .. err_message)
print("text_type = " .. text_type)