This is a static archive of our old Q&A Site. Please post any new questions and answers at ask.wireshark.org.

How can we implement exception handling using Lua?

0

If we want to develop our own plugin using Lua. How we can use exception handling in that?

asked 13 Mar '15, 02:14

ankit's gravatar image

ankit
65232328
accept rate: 25%

edited 14 Mar '15, 11:19

helloworld's gravatar image

helloworld
3.1k42041


One Answer:

1

To catch Lua exceptions, use pcall as described in Lua docs (copied here):

If you need to handle errors in Lua, you should use the pcall function (protected call) to encapsulate your code.

Suppose you want to run a piece of Lua code and to catch any error raised while running that code. Your first step is to encapsulate that piece of code in a function; let us call it foo:

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

Of course, you can call pcall with an anonymous function:

if pcall(function () ... end) then ...
else ...

The pcall function calls its first argument in protected mode, so that it catches any errors while the function is running. If there are no errors, pcall returns true, plus any values returned by the call. Otherwise, it returns false, plus the error message.

Despite its name, the error message does not have to be a string. Any Lua value that you pass to error will be returned by pcall:

local status, err = pcall(function () error({code=121}) end)
print(err.code)  -->  121

These mechanisms provide all we need to do exception handling in Lua. We throw an exception with error and catch it with pcall. The error message identifies the kind or error.

answered 14 Mar ‘15, 11:40

helloworld's gravatar image

helloworld
3.1k42041
accept rate: 28%