I'm playing around with AngelScript, and one thing I can't seem to wrap my head around is how to catch exceptions thrown from C++ but called from AngelScript. Here's what I've got so far:
// test.as
void main()
{
print("Calling throwSomething...");
throwSomething();
print("Call finished");
}
void print(string)
and void throwSomething()
are two functions registered to the engine, source below. As per the AngelScript docs:
Application functions and class methods registered with the script engine are allowed to throw C++ exceptions. The virtual machine will automatically catch any C++ exception, abort the script execution, and return control to the application.
Here's the example code provided for handling exceptions:
asIScriptContext *ctx = engine->CreateContext();
ctx->Prepare(engine->GetModule("test")->GetFunctionByName("func"));
int r = ctx->Execute();
if( r == asEXECUTION_EXCEPTION )
{
string err = ctx->GetExceptionString();
if( err == "Caught an exception from the application" )
{
// An application function threw an exception while being invoked from the script
...
}
}
I pretty much verbatim copied this code into my editor and tried to run it. Unfortunately, even though I wrapped the call to Execute
in a try-catch block, I still get this output:
(AngelScript) Calling throwSomething...
(C++) throwSomething Entered...
libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: Assert(1 == 0) failed, line 68
Abort trap: 6
For completeness' sake, here's the code for throwSomething
and print
:
void throwSomething()
{
cout << "(C++) throwSomething Entered...\n";
Assert(1 == 0); // will throw an exception
cout << "(C++) throwSomething Exiting...\n";
}
void print(string s)
{
cout << "(AngelScript) " << s << "\n";
}
So, I'm feeling a little stuck. I tried registering an exception translation function (see linked doc) in hopes that would help, but I still got the same results. From looking at Xcode's debugger, the exception appears to happen in the main thread-- so I'm unsure why neither my code or the code in the AngelScript library itself catches the exception.
So, I guess my question is: 1) how can I either catch the exception within my program, or 2) If I can't catch it from within the program, how can I otherwise handle it without the program crashing?
I'm running this on a ~2015 MacBook Pro running MacOS 10.14.6 and AngelScript version 2.33.0, if that's relevant.