Throwing a JavaScript exception from C++ code using Google V8

Viewed 7902

I'm programming a JavaScript application which accesses some C++ code over Google's V8.

Everything works fine, but I couldn't figure out how I can throw a JavaScript exception which can be catched in the JavaScript code from the C++ method.

For example, if I have a function in C++ like

...
using namespace std;
using namespace v8;
...
static Handle<Value> jsHello(const Arguments& args) {
    String::Utf8Value input(args[0]);
    if (input == "Hello") {
        string result = "world";
        return String::New(result.c_str());
    } else {
        // throw exception
    }
}
...
    global->Set(String::New("hello"), FunctionTemplate::New(jsHello));
    Persistent<Context> context = Context::New(NULL, global);
...

exposed to JavaScript, I'ld like to use it in the JavaScript code like

try {
    hello("throw me some exception!");
} catch (e) {
    // catched it!
}

What is the correct way to throw a V8-exception out of the C++ code?

2 Answers
Related