假设我有这个代码:
Local<Script> script = Script::Compile(String::New("x1 = 1;"), String::New("main.js"));
printf("before run\n");
script->Run();
printf("after run\n");
上下文是之前创建和输入的。
这段代码的输出是:
before run
after run
正如预期的那样。source
但是,如果将一些包含语法错误(例如, )的javascript 代码放入其中,".x11 = 1"
则输出为:
main.js:0: Uncaught SyntaxError: Unexpected token .
before execution.
Segmentation fault (core dumped)
如果编译有错误,也许我不应该打电话Run
,但如何检查呢?
另外:(来自Getting Starget 的代码 - Chrome V8 + 有语法错误的代码 = 相同的东西)
#include <v8.h>
using namespace v8;
int main(int argc, char* argv[]) {
// Get the default Isolate created at startup.
Isolate* isolate = Isolate::GetCurrent();
// Create a stack-allocated handle scope.
HandleScope handle_scope(isolate);
// Create a new context.
Handle<Context> context = Context::New(isolate);
// Here's how you could create a Persistent handle to the context, if needed.
Persistent<Context> persistent_context(isolate, context);
// Enter the created context for compiling and
// running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
Handle<String> source = String::New(".>make.some.syntax.errors<");
// Compile the source code.
Handle<Script> script = Script::Compile(source);
// Run the script to get the result.
Handle<Value> result = script->Run();
// The persistent handle needs to be eventually disposed.
persistent_context.Dispose();
// Convert the result to an ASCII string and print it.
String::AsciiValue ascii(result);
printf("%s\n", *ascii);
return 0;
}