trycatch

The trycatch library is a simple library used to create an error handling approach similar to C/C++/C#/etc. try, catch and finally calls.

The trycatch library is based on code by djfdyuruiry. https://github.com/djfdyuruiry/lua-try-catch-finally

Using The Library

Addons should require the common library if they wish to use the trycatch library. It is included automatically with it.

1require 'common';

Functions

try

Implements a try, catch, finally style statement.

1try(func);
Parameter NameTypeDescription
funcfunctionThe function to attempt to run protected from errors.
Returns
None.

Examples

Below are a few examples of using try.

You can use try without any catch or finally callback, however this is not ideal as it will just hide errors that should otherwise be fixed instead of just ignored.

1try(function ()
2    error('Attempt to raise an error..');
3end)

You can use try with a catch callback which will be passed the full error information from when the initial call failed.

1try(function ()
2    error('Attempt to raise an error..');
3end).catch(function (e)
4    -- Print the error information..
5    print(e);
6end)

In some cases, you may want to cleanup objects that were potentially initialized/used with the function being caught for errors. This is generally done in a ‘finally’ block which runs after the try and catch handlers are invoked, giving a place to ensure cleanup can take place.

1try(function ()
2    error('Attempt to raise an error..');
3end).catch(function (e)
4    -- Print the error information..
5    print(e);
6end).finally(function ()
7    -- Perform any needed cleanup here..
8    print('Cleanup can happen here..')
9end);