26

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?

Etan
  • 17,014
  • 17
  • 89
  • 148

2 Answers2

29

Edit: This answer is for older versions of V8. For current versions, see Sutarmin Anton's Answer.


return v8::ThrowException(v8::String::New("Exception message"));

You can also throw a more specific exception with the static functions in v8::Exception:

return v8::ThrowException(v8::Exception::RangeError(v8::String::New("...")));
return v8::ThrowException(v8::Exception::ReferenceError(v8::String::New("...")));
return v8::ThrowException(v8::Exception::SyntaxError(v8::String::New("...")));
return v8::ThrowException(v8::Exception::TypeError(v8::String::New("...")));
return v8::ThrowException(v8::Exception::Error(v8::String::New("...")));
Community
  • 1
  • 1
Matthew Crumley
  • 101,441
  • 24
  • 103
  • 129
15

In last versions of v8 Mattew's answer doesn't work. Now in every function that you use you get an Isolate object.

New exception raising with Isolate object look like this:

Isolate* isolate = Isolate::GetCurrent();
isolate->ThrowException(String::NewFromUtf8(isolate, "error string here"));
xaxxon
  • 19,189
  • 5
  • 50
  • 80
Anton Sutarmin
  • 807
  • 8
  • 15