RE: C++ exceptions

  • From: Alex Guo <chessnut@xxxxxxxxxxx>
  • To: "luajit@xxxxxxxxxxxxx" <luajit@xxxxxxxxxxxxx>
  • Date: Mon, 13 Jul 2015 16:48:51 -0400




Thanks Tudor, that makes a lot of sense.
I also realized after sending my email that my code snippet wasn't throwing an
error -- lua_error() doesn't do that. However, even the following code fragment
results in a funky SEGFAULT:
lua_State *my_lua = lua_open(); try { int result = luaL_dostring(my_lua,
"end end end end end"); LOG(INFO) << "Lua result: " << result; if
(result) { throw std::exception("Your face!"); } } catch (const
std::exception& err) { LOG(INFO) << "Oops: " << err.what(); }
lua_close(my_lua);

Date: Mon, 13 Jul 2015 13:20:07 -0700
Subject: Re: C++ exceptions
From: tudorb@xxxxxxxxx
To: luajit@xxxxxxxxxxxxx

On Mon, Jul 13, 2015 at 11:27 AM, Alex Guo <chessnut@xxxxxxxxxxx> wrote:
The problem I'm trying to solve is throwing C++ exceptions. Here is some sample
code that works in a small C++ unit test, but fails in a large C++ code base
(40k LOC, linked against several other binaries that exceed several hundred
thousand LOC).
The error is not thrown as a C++ exception, but as a foreign ABI exception.
(Similar to the way Java exceptions are thrown when embedding Java in a C++
program).
The C++ runtime can catch it (but it's not derived from std::exception, so
you'll have to catch it with catch (...)) and rethrow it (using "throw;"
without an exception object argument), but you can't inspect it in any way. You
can retrieve the error message from the top of the Lua stack, assuming that you
know what lua_State* to use, and assuming that you're 100% sure that the
foreign exception that you caught is a Lua exception... (neither of those
assumptions were obviously true in my case when I needed this)
C++11 won't save you either; std::current_exception() will return an empty
exception_ptr in the catch (...) block, as if no exception were being handled.
If you really want to transform Lua errors into C++ exceptions, you'll have to
use lua_pcall / lua_cpcall and rethrow the exception yourself.
-Tudor.

Other related posts: