-
Notifications
You must be signed in to change notification settings - Fork 5
Error Handling
By default, all exceptions thrown within LibraryLink functions will be caught and handled by wll-interface. Typical exceptions in wll-interface includes std::exception
(and its derive classes) in C++ STL, and six classes implemented by wll-interface, corresponding to six types of errors in native LibraryLink:
wll::library_type_error
wll::library_rank_error
wll::library_dimension_error
wll::library_numerical_error
wll::library_memory_error
wll::library_function_error
In the following example, an exception will be thrown with an optional message that describes what has happened,
throw wll::library_numerical_error("sqrt(x) with x < 0");
If this exception is thrown, the result shown in Mathematica will be LibraryFunctionError["LIBRARY_NUMERICAL_ERROR", 4]
, indicating a numerical error being triggered. To retrieve the exception message, we first load wll_exception_msg
function:
exception = LibraryFunctionLoad[(*libpath*), "wll_exception_msg", {}, "UTF8String"];
Then evaluate exception[]
, and get the information about the most recent exception:
Wolfram Library Exception
sqrt(x) with x < 0
If you want to disable wll-interface exception handling, define WLL_DISABLE_EXCEPTION_HANDLING
before #include
statement:
#define WLL_DISABLE_EXCEPTION_HANDLING
#include "wll_interface.h"
In this case, uncaught exceptions will be exposed to the Wolfram Kernel, where they can be analyzed by the debugger.
wll-interface will perform checks frequently while it is running. When wll-interface detects an error, an exception will often be thrown, or an assertion failure will be triggered. Generally speaking, as assertion failures can cause Wolfram Kernel to crash, they are used to detect errors can be expected and avoided. For this reason, they will only be triggered in the debug mode (NDEBUG
is not defined).
In the following example, we construct a tensor on C++ side as shared
(but shared
tensor can only be possible when construct by MTensor
), so an assertion failure will crash the Wolfram Kernel.
wll::tensor<int, 3> t({3, 4, 5}, wll::memory_type::shared);
wll-interface has defined a variable wll::global_log
, a string stream that can be used to output messages to Wolfram Language.
On C++ side, we can insert the messages to wll::global_log
, e.g.
wll::list<int> my_list({}, {1, 2, 3, 4, 5, 6});
wll::global_log << "size of my_list is " << my_list.size() << '\n';
To interact with global_log
, we need to load relevant LibraryLink functions,
logcontent = LibraryFunctionLoad[(*libpath*), "wll_log_content", {}, "UTF8String"];
logclear = LibraryFunctionLoad[(*libpath*), "wll_log_clear", {}, "Void"];
Then evaluate logcontent[]
to show the message:
size of my_list is 6
Evaluate logclear[]
to clear the log.