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?
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("...")));