Is there any exception handling?

Lua programmers often prefer to return errors from functions. The usual convention is that if the function returns nil or false then the second value returned is the error message.

function sqr(n)
 if type(n) ~= 'number' then
 return nil,'parameter must be a number'
 else
 return n*n
 end end

Of course, we know that in large applications it is often better to let the error immediately break execution and then to catch it outside. This allows us to write code that is not so cluttered with conditional error checking. Lua does allow a function to be called in a protected environment using pcall. Wrapping up the code in an anonymous function gives us the equivalent to a try/catch construct:

local status,err = pcall(function()
 t.alpha = 2.0 -- will throw an error if t is nil or not a table end)
if not status then
 print(err)
end

This does seem a little clunky, and the temptation to find a cleaner syntax can be irresistible. MetaLua provides an elegant solution using compile-time macros.

One benefit of the explicit form here is that the cost of exception handling becomes clear; it involves creating a closure for the execution of each protected block.

The equivalent of throw or raise is just the function error.

The object 'thrown' by error can be any Lua object, but if it is not a string it should be convertible into a string. Also, Lua 5.1 does not apply __tostring to such error messages when reporting an error. Consider:

MT = {__tostring = function(t) return 'me' end}
t = {1,2}
setmetatable(t,MT)
error(t)

With Lua 5.1, the reported error is "(error object is not a string)" and with Lua 5.2 it is "me", as expected. This behaviour is not a problem with errors caught explicitly with pcall, since you can deal with the error object directly.



Back