当前位置: 首页>>代码示例>>C++>>正文


C++ TryCatch类代码示例

本文整理汇总了C++中TryCatch的典型用法代码示例。如果您正苦于以下问题:C++ TryCatch类的具体用法?C++ TryCatch怎么用?C++ TryCatch使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了TryCatch类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: context_eval

// [[Rcpp::export]]
std::string context_eval(std::string src, Rcpp::XPtr< v8::Persistent<v8::Context> > ctx){
  // Test if context still exists
  if(!ctx)
    throw std::runtime_error("Context has been disposed.");

  // Create a scope
  HandleScope handle_scope;
  Context::Scope context_scope(*ctx);

  // Compile source code
  TryCatch trycatch;
  Handle<Script> script = compile_source(src);
  if(script.IsEmpty()) {
    Local<Value> exception = trycatch.Exception();
    String::AsciiValue exception_str(exception);
    throw std::invalid_argument(*exception_str);
  }

  // Run the script to get the result.
  Handle<Value> result = script->Run();
  if(result.IsEmpty()){
    Local<Value> exception = trycatch.Exception();
    String::AsciiValue exception_str(exception);
    throw std::runtime_error(*exception_str);
  }

  // Convert result to UTF8.
  String::Utf8Value utf8(result);
  return *utf8;
}
开发者ID:kenahoo,项目名称:V8,代码行数:31,代码来源:V8.cpp

示例2: DEFINE_METHOD

/* static */
void V8Runtime::bootstrap(Local<Object> global)
{
	EventEmitter::Initialize();
	krollGlobalObject = Persistent<Object>::New(Object::New());

	DEFINE_METHOD(krollGlobalObject, "log", krollLog);
	DEFINE_METHOD(krollGlobalObject, "binding", KrollBindings::getBinding);
	DEFINE_TEMPLATE(krollGlobalObject, "EventEmitter", EventEmitter::constructorTemplate);

	krollGlobalObject->Set(String::NewSymbol("runtime"), String::New("v8"));

	LOG_TIMER(TAG, "Executing kroll.js");

	TryCatch tryCatch;
	Handle<Value> result = V8Util::executeString(KrollBindings::getMainSource(), String::New("kroll.js"));

	if (tryCatch.HasCaught()) {
		V8Util::reportException(tryCatch, true);
	}
	if (!result->IsFunction()) {
		LOGF(TAG, "kroll.js result is not a function");
		V8Util::reportException(tryCatch, true);
	}

	Handle<Function> mainFunction = Handle<Function>::Cast(result);
	Local<Value> args[] = { Local<Value>::New(krollGlobalObject) };
	mainFunction->Call(global, 1, args);

	if (tryCatch.HasCaught()) {
		V8Util::reportException(tryCatch, true);
		LOGE(TAG, "Caught exception while bootstrapping Kroll");
	}
}
开发者ID:b0morris,项目名称:titanium_mobile,代码行数:34,代码来源:V8Runtime.cpp

示例3: wWinMain

int __stdcall wWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPTSTR lpCmdLine,int nCmdShow){
	int rt = -1;
	initContext();
	HandleScope store;
	runJSRes(IDR_JS_STRUCT,L"app.lib");
	Handle<Value> result = runJSFile(L"main.js",L"utf-8");
	if(!result.IsEmpty()){//只有出错的时候才会返回Empty, 否则即使没有返回值, result仍然是Undefined.
		Local<Object> gObj = getGlobal();
		Local<Function> main = GetJSVariant<Function>(gObj,L"main");
		if(main.IsEmpty()){
			//InnerMsg(L"没有发现 main 函数",MT_ERROR);
		}else if(!main->IsFunction()){
			//InnerMsg(L"main 不是函数",MT_ERROR);
		}else{
			TryCatch err;
			Handle<Value> args[1];
			args[0] = String::New((uint16_t*)lpCmdLine);
			Local<Value> r = main->Call(gObj,1,args);
			if(!err.Exception().IsEmpty()){
				ReportError(err);
			}else
				rt = r->Int32Value();
		}
	}
	releaseContext();
	return rt;
}
开发者ID:pgmsoul,项目名称:JSApp,代码行数:27,代码来源:main.cpp

示例4: NativeScriptException

Local<Object> Module::LoadData(Isolate *isolate, const string& path)
{
	Local<Object> json;

	auto jsonData = File::ReadText(path);

	TryCatch tc;

	auto jsonStr = ConvertToV8String(jsonData);

	auto maybeValue = JSON::Parse(isolate, jsonStr);

	if (maybeValue.IsEmpty() || tc.HasCaught())
	{
		string errMsg = "Cannot parse JSON file " + path;
		throw NativeScriptException(tc, errMsg);
	}

	auto value = maybeValue.ToLocalChecked();

	if (!value->IsObject())
	{
		string errMsg = "JSON is not valid, file=" + path;
		throw NativeScriptException(errMsg);
	}

	json = value.As<Object>();

	return json;
}
开发者ID:PeterStaev,项目名称:android-runtime,代码行数:30,代码来源:Module.cpp

示例5: execute_string

extern "C" Handle<Value> execute_string(Persistent<Context> context,
					const char* s,
					bool* is_exception) {
    // Create a stack-allocated handle scope.
    HandleScope handle_scope;

    // 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(s);

    // Compile it
    Handle<Script> script = Script::Compile(source);

    // try-catch handler
    TryCatch trycatch;
    // Run it
    Persistent<Value> result = Persistent<Value>::New(script->Run());

    // Script->Run() returns an empty handle if the code threw an exception
    if (result.IsEmpty()) {
	*is_exception = true;
	Handle<Value> exception = trycatch.Exception();
	// String::AsciiValue exception_str(exception);
	return Persistent<Value>::New(exception);	
    }
    
    return result;
}
开发者ID:edumunoz,项目名称:MiXture,代码行数:31,代码来源:v8_helper.cpp

示例6: v8test_eval

bool v8test_eval()
{
    BEGINTEST();

    HandleScope handle_scope;
    Persistent<Context> context = Context::New();
    Context::Scope context_scope(context);

    Local<Object> qmlglobal = Object::New();
    qmlglobal->Set(String::New("a"), Integer::New(1922));

    Local<Script> script = Script::Compile(String::New("eval(\"a\")"), NULL, NULL, 
                                           Handle<String>(), Script::QmlMode);
    
    TryCatch tc;
    Local<Value> result = script->Run(qmlglobal);

    VERIFY(!tc.HasCaught());
    VERIFY(result->Int32Value() == 1922);

cleanup:
    context.Dispose();

    ENDTEST();
}
开发者ID:yinyunqiao,项目名称:qtdeclarative,代码行数:25,代码来源:v8test.cpp

示例7: exception_str

std::string V8Engine::compileScript(std::string script)
{
    HandleScope handleScope;
    TryCatch tc;

    Local<String> source = String::New(script.c_str());

    // Compile the source code.

    Local<Script> code = Script::Compile(source);
    if (!code.IsEmpty())
        return "";

    // There were errors, return them

    std::string ret = "";

    Handle<Object> exception = tc.Exception()->ToObject();
    String::AsciiValue exception_str(exception);

    ret += *exception_str; ret += "\n";

    Local<Message> message = tc.Message();

    ret += *(v8::String::Utf8Value( message->Get() )); ret += "\n";
    ret += "Source line: "; ret += *(v8::String::Utf8Value( message->GetSourceLine() )); ret += "\n";
    ret += "Source line number: "; ret += Utility::toString(message->GetLineNumber()); ret += "\n";

    return ret;
}
开发者ID:Amplifying,项目名称:intensityengine,代码行数:30,代码来源:script_engine_v8.cpp

示例8: function

        void JSAttributeTest::requestValueWithCallbackTestOnlyFirstTime(std::shared_ptr<JSZAttribute> &jsZAttribute, std::shared_ptr<ZCLAttribute> attributeMock,
                                                                        Callbacks &changeSignal) {
            ZDevice zDevice{createZDevice()};
            std::stringstream stream;
            stream << "var f = function (){\n";
            stream << "    var log = Log();\n";
            stream << "    log.info('callback called')";
            stream << "};\n";

            stream << zAttributeVariable << "\n";
            stream << "var b = a.requestValue(f);\n";
            V8_SETUP
            jsZAttribute->initJsObjectsTemplate(isolate, global);
            jsLog->initJsObjectsTemplate(isolate, global);

            setInitExpectation(zDevice, attributeMock);

            TryCatch tryCatch;
            v8::Local<v8::Value> result = runScript(stream.str());
            if (tryCatch.HasCaught()) {
                String::Utf8Value value(tryCatch.Message()->Get());
            }
            ASSERT_THAT(result.IsEmpty(), false);
            ASSERT_THAT(result->IsUndefined(), true);

            changeSignal();

            result = runScript("");
            result = runScript("");

            ASSERT_THAT(log.empty(), false);
            Log::LogData logData = log.get();
            ASSERT_THAT(logData.msg, StrEq("callback called"));
            ASSERT_THAT(log.empty(), true);
        }
开发者ID:paoloach,项目名称:zdomus,代码行数:35,代码来源:JSAttributeTest.cpp

示例9: scope

void ScriptGame::_mouseMoved( const float x, const float y )
{
	HandleScope hs;
	PersistentContext ctx = MagnetiteCore::Singleton->getScriptManager()->getContext();
	Context::Scope scope( ctx );
	
	bool eval = false;
	if( !mScriptObject.IsEmpty() && mScriptObject->Has( String::New("mouseMoved") ) )
	{
		Local<Value> onLoadVal = mScriptObject->Get( String::New("mouseMoved") );
		if( onLoadVal->IsFunction() )
		{
			TryCatch ct;
			Local<Function> onLoad = Local<Function>::Cast( onLoadVal );
			Handle<Value> args[2];
			args[0] = Number::New(x);
			args[1] = Number::New(y);
			auto r = onLoad->Call( mScriptObject, 2, args );
			if( r.IsEmpty() ) {
				Util::log(strize(ct.StackTrace()));
			}
			else 
			{
				eval = r->BooleanValue();
			}
		}
	}
	if(!eval && getLocalPlayer() ) {
		mPlayer->getCamera()->pitch( y );
		mPlayer->getCamera()->yaw( x );
	}
}
开发者ID:zuzak,项目名称:Magnetite,代码行数:32,代码来源:ScriptGame.cpp

示例10: ENTER_V8

JNIEXPORT jobject JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeEvalString
	(JNIEnv *env, jobject self, jstring source, jstring filename)
{
	ENTER_V8(V8Runtime::globalContext);
	titanium::JNIScope jniScope(env);

	Handle<Value> jsSource = TypeConverter::javaStringToJsString(env, source);
	if (jsSource.IsEmpty() || !jsSource->IsString()) {
		LOGE(TAG, "Error converting Javascript string, aborting evalString");
		return NULL;
	}

	Handle<Value> jsFilename = TypeConverter::javaStringToJsString(env, filename);

	TryCatch tryCatch;
	Handle<Script> script = Script::Compile(jsSource->ToString(), jsFilename);
	Local<Value> result = script->Run();

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(tryCatch);
		V8Util::reportException(tryCatch, true);
		return NULL;
	}

	return TypeConverter::jsValueToJavaObject(env, result);
}
开发者ID:SreenuDevireddy,项目名称:titanium_mobile,代码行数:26,代码来源:V8Runtime.cpp

示例11: EIO_AfterIndex

    static int EIO_AfterIndex(eio_req* req) {
        HandleScope scope;
        index_baton_t* baton = static_cast<index_baton_t*>(req->data);
        ev_unref(EV_DEFAULT_UC);
        baton->lucene->Unref();

        Handle<Value> argv[2];

        if (!baton->error.empty()) {
            argv[0] = v8::String::New(baton->error.c_str());
            argv[1] = Undefined();
        }
        else {
            argv[0] = Undefined();
            argv[1] = v8::Integer::NewFromUnsigned((uint32_t)baton->indexTime);
        }

        TryCatch tryCatch;

        baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);

        if (tryCatch.HasCaught()) {
            FatalException(tryCatch);
        }

        baton->callback.Dispose();
        delete baton->index;
        delete baton;
        return 0;
    }
开发者ID:temas,项目名称:node-lucene,代码行数:30,代码来源:clucene_bindings.cpp

示例12: EIO_AfterSearch

    static int EIO_AfterSearch(eio_req* req)
    {
        HandleScope scope;
        search_baton_t* baton = static_cast<search_baton_t*>(req->data);
        ev_unref(EV_DEFAULT_UC);
        baton->lucene->Unref();

        Handle<Value> argv[2];

        if (baton->error.empty()) {
            argv[0] = Null(); // Error arg, defaulting to no error
            argv[1] = baton->results;
        } else {
            argv[0] = String::New(baton->error.c_str());
            argv[1] = Null();
        }

        TryCatch tryCatch;

        baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);

        if (tryCatch.HasCaught()) {
            FatalException(tryCatch);
        }
        
        baton->callback.Dispose();
        if (!baton->results.IsEmpty()) baton->results.Dispose();

        delete baton->index;
        delete baton->search;
        delete baton;

        return 0;
    }
开发者ID:temas,项目名称:node-lucene,代码行数:34,代码来源:clucene_bindings.cpp

示例13: DBG

void CoreClrFuncInvokeContext::InvokeCallback(void* data)
{
	DBG("CoreClrFuncInvokeContext::InvokeCallback");

	CoreClrFuncInvokeContext* context = (CoreClrFuncInvokeContext*)data;
	v8::Handle<v8::Value> callbackData = NanNull();
	v8::Handle<v8::Value> errors = NanNull();

	if (context->taskState == TaskStatus::Faulted)
	{
		errors = CoreClrFunc::MarshalCLRToV8(context->resultData, context->resultType);
	}

	else
	{
		callbackData = CoreClrFunc::MarshalCLRToV8(context->resultData, context->resultType);
	}

	Handle<Value> argv[] = { errors, callbackData };
	int argc = 2;

	TryCatch tryCatch;
	NanNew<v8::Function>(*(context->callback))->Call(NanGetCurrentContext()->Global(), argc, argv);
	delete context;

	if (tryCatch.HasCaught())
	{
		node::FatalException(tryCatch);
	}
}
开发者ID:DerGroncki,项目名称:edge,代码行数:30,代码来源:coreclrfuncinvokecontext.cpp

示例14: Exception

v8::Handle<v8::String> V8::toJson(v8::Handle<v8::Value> value) {
	HandleScope scope;

	Handle<Context> context = Context::GetCurrent();
	Handle<Object> global = context->Global();

	Handle<Object> JSON = global->Get(String::New("JSON"))->ToObject();
	Handle<Function> JSON_stringify = Handle<Function>::Cast(JSON->Get(String::New("stringify")));

	TryCatch exception;

	Handle<Value> argv[] = {
		value,
		v8::Null(),
		v8::String::New("\t")
	};

	if (exception.HasCaught()) {
		throw chi::Exception(chi::V8::ReportException(exception));
	}

	Handle<Value> stringified = JSON_stringify->Call(JSON_stringify, 3, argv);

	if (exception.HasCaught()) {
		throw chi::Exception(chi::V8::ReportException(exception));
	}

	return scope.Close(stringified.As<String>());
}
开发者ID:cha0s,项目名称:Worlds-Beyond,代码行数:29,代码来源:wbv8.cpp

示例15: Event

    void Event(Pollpri * p, int revents) {
        HandleScope scope;
        PRINTF("fd = %d, epfd = %d, revents = 0x%0x\n", fd, epfd, revents);
        if(revents != EV_READ) {
            printf("fd = %d, epfd = %d, revents = 0x%0x\n", fd, epfd, revents);
            return;
        }
        
        int m = 0;
        char buf[64];
        m = lseek(fd, 0, SEEK_SET);
        PRINTF("seek(%d) %d bytes: %s\n", fd, m, strerror(errno));
        m = read(fd, &buf, 63);
        buf[m] = 0;
        PRINTF("read(%d) %d bytes (%s): %s\n", fd, m, buf, strerror(errno));

        Local<Value> emit_v = handle_->Get(String::NewSymbol("emit"));
        assert(emit_v->IsFunction());
        Local<Function> emit_f = emit_v.As<Function>();
        
        Handle<Value> argv[2];
        argv[0] = String::New("edge");
        argv[1] = String::New(buf);
        
        TryCatch tc;
        
        emit_f->Call(handle_, 2, argv);

        if(tc.HasCaught()) {
            FatalException(tc);
        }
    }
开发者ID:KiL89,项目名称:bonescript,代码行数:32,代码来源:misc.cpp


注:本文中的TryCatch类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。