最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JS調用C++函數(shù)拋出異常及捕捉異常詳解

 更新時間:2021年08月19日 11:36:42   作者:永遠的魔術1號  
這篇文章主要介紹了js調用C++函數(shù)的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

本文講述如何利用v8::TryCatch捕捉js代碼中發(fā)生的異常。

首先,聲明TryCatch對象。

v8::TryCatch trycatch( isolate );

然后,定義拋出異常的函數(shù):

void ThrowException( const v8::FunctionCallbackInfo<v8::Value>& info ) {
    v8::Isolate* isolate = info.GetIsolate();
    v8::HandleScope scope( isolate );

    v8::Local<v8::Value> exc = v8::Local<v8::Value>::New( info.GetIsolate(),
        v8::Exception::Error( v8::String::NewFromUtf8( isolate, "throw an exception" ).ToLocalChecked() ) );
    info.GetIsolate()->ThrowException( exc );
}

設置訪問器訪問C++函數(shù):

v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New( isolate );
global->Set( isolate, "throwException",
    v8::FunctionTemplate::New( isolate, ThrowException ) );

因為異常發(fā)生在執(zhí)行js文件期間,所以需要在Run函數(shù)后判斷是否有異常發(fā)生。這里Run的結果沒有繼續(xù)調用ToLocalChecked(),因為result為NULL。

// Run the script to get the result.
v8::MaybeLocal<v8::Value> result = script->Run( context );
if ( trycatch.HasCaught() ) {
    v8::Local<v8::Message> message = trycatch.Message();
    ResolveMessage( message );
    return -1;
}

這樣就可以在js文件中使用C++函數(shù)拋出異常,并解析異常信息。

main.cpp

// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "include/libplatform/libplatform.h"
#include "include/v8.h"

#include "point.h"

using namespace std;
using namespace v8;

const std::string fileName = "file.js";

// Reads a file into a v8 string.
MaybeLocal<String> ReadFile( Isolate* isolate, const string& name ) {
    FILE* file = fopen( name.c_str(), "rb" );
    if ( file == NULL ) return MaybeLocal<String>();

    fseek( file, 0, SEEK_END );
    size_t size = ftell( file );
    rewind( file );

    std::unique_ptr<char> chars( new char[size + 1] );
    chars.get()[size] = '\0';
    for ( size_t i = 0; i < size;) {
        i += fread( &chars.get()[i], 1, size - i, file );
        if ( ferror( file ) ) {
            fclose( file );
            return MaybeLocal<String>();
        }
    }
    fclose( file );
    MaybeLocal<String> result = String::NewFromUtf8(
        isolate, chars.get(), NewStringType::kNormal, static_cast<int>(size) );
    return result;
}

void ThrowException( const v8::FunctionCallbackInfo<v8::Value>& info ) {
    v8::Isolate* isolate = info.GetIsolate();
    v8::HandleScope scope( isolate );

    v8::Local<v8::Value> exc = v8::Local<v8::Value>::New( info.GetIsolate(),
        v8::Exception::Error( v8::String::NewFromUtf8( isolate, "throw an exception" ).ToLocalChecked() ) );
    info.GetIsolate()->ThrowException( exc );
}

void ResolveMessage( v8::Local<v8::Message> message ) {
    v8::Isolate* isolate = message->GetIsolate();
    v8::Local<v8::Context> context = isolate->GetCurrentContext();

    int lineNum = message->GetLineNumber( context ).ToChecked();
    v8::String::Utf8Value err_msg( isolate, message->Get() );
    v8::String::Utf8Value err_src( isolate, message->GetSourceLine( context ).ToLocalChecked() );

    printf( "line %d, [error] %s, [error source] %s", lineNum, *err_msg, *err_src );
}

int main( int argc, char* argv[] ) {
    // Initialize V8.
    v8::V8::InitializeICUDefaultLocation( argv[0] );
    v8::V8::InitializeExternalStartupData( argv[0] );
    std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
    v8::V8::InitializePlatform( platform.get() );
    v8::V8::Initialize();

    // Create a new Isolate and make it the current one.
    v8::Isolate::CreateParams create_params;
    create_params.array_buffer_allocator =
        v8::ArrayBuffer::Allocator::NewDefaultAllocator();
    v8::Isolate* isolate = v8::Isolate::New( create_params );
    {
        v8::Isolate::Scope isolate_scope( isolate );

        // Create a stack-allocated handle scope.
        v8::HandleScope handle_scope( isolate );

        v8::TryCatch trycatch( isolate );

        v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New( isolate );
        global->Set( isolate, "throwException",
            v8::FunctionTemplate::New( isolate, ThrowException ) );

        // Create a new context.
        v8::Local<v8::Context> context = v8::Context::New( isolate, nullptr, global );

        // Enter the context for compiling and running the hello world script.
        v8::Context::Scope context_scope( context );

        {
            // Create a string containing the JavaScript source code.
            v8::Local<v8::String> source;
            if ( !ReadFile( isolate, fileName ).ToLocal( &source ) ) {
                fprintf( stderr, "Error reading '%s'.\n", fileName.c_str() );
                return -1;
            }

            // Compile the source code.
            v8::Local<v8::Script> script =
                v8::Script::Compile( context, source ).ToLocalChecked();

            // Run the script to get the result.
            v8::MaybeLocal<v8::Value> result = script->Run( context );
            if ( trycatch.HasCaught() ) {
                v8::Local<v8::Message> message = trycatch.Message();
                ResolveMessage( message );
                return -1;
            }
        }
    }

    // Dispose the isolate and tear down V8.
    isolate->Dispose();
    v8::V8::Dispose();
    v8::V8::ShutdownPlatform();
    delete create_params.array_buffer_allocator;
    return 0;
}

file.js

throwException();

運行結果:

總結

本篇文章就到這里了,希望能給你帶來幫助,也希望您能夠多多關注腳本之家的更多內(nèi)容!

相關文章

  • 關于C++的重載運算符和重載函數(shù)

    關于C++的重載運算符和重載函數(shù)

    一般來說,重載運算符在實際的項目開發(fā)中會經(jīng)常的用到,但如果某些自定義類型通過簡短幾行代碼重載一些常用的運算符(如:+-*/),就能讓編程工作帶來方便,需要的朋友可以參考下本文
    2023-05-05
  • C++模板類的用法

    C++模板類的用法

    這篇文章主要介紹了C++模板類的用法,實例講述了模板類的概念及相關用法,需要的朋友可以參考下
    2014-10-10
  • 解析VC中創(chuàng)建DLL,導出全局變量,函數(shù)和類的深入分析

    解析VC中創(chuàng)建DLL,導出全局變量,函數(shù)和類的深入分析

    本篇文章是對VC中創(chuàng)建DLL,導出全局變量,函數(shù)和類進行了詳細的分析介紹,需要的朋友參考下
    2013-05-05
  • Opencv分水嶺算法學習

    Opencv分水嶺算法學習

    這篇文章主要為大家詳細介紹了Opencv分水嶺算法的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • 詳解C++設計模式編程中責任鏈模式的應用

    詳解C++設計模式編程中責任鏈模式的應用

    這篇文章主要介紹了C++設計模式編程中責任鏈模式的應用,責任鏈模式使多個對象都有機會處理請求,從而避免請求的發(fā)送者和接收者之間的耦合關系,需要的朋友可以參考下
    2016-03-03
  • C++從txt文件中讀取二維的數(shù)組方法

    C++從txt文件中讀取二維的數(shù)組方法

    今天小編就為大家分享一篇C++從txt文件中讀取二維的數(shù)組方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • 使用C語言順序表數(shù)據(jù)結構實現(xiàn)棧的代碼示例

    使用C語言順序表數(shù)據(jù)結構實現(xiàn)棧的代碼示例

    這篇文章主要給大家介紹了如何使用C語言順序表數(shù)據(jù)結構實現(xiàn)棧,文章通過代碼示例介紹的非常詳細,對大家的學習或工作有一定的參考價值,需要的朋友可以參考下
    2023-09-09
  • 深入解析C++的WNDCLASS結構體及其在Windows中的應用

    深入解析C++的WNDCLASS結構體及其在Windows中的應用

    這篇文章主要介紹了C++的WNDCLASS結構體及其在Windows中的應用,WNDCLASS被用來定義窗口,文中介紹了其諸多屬性,需要的朋友可以參考下
    2016-01-01
  • C++非遞歸建立二叉樹實例

    C++非遞歸建立二叉樹實例

    這篇文章主要介紹了C++非遞歸建立二叉樹的方法,實例分析了二叉樹的原理與C++實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-04-04
  • C語言中strcmp的實現(xiàn)原型

    C語言中strcmp的實現(xiàn)原型

    這篇文章主要介紹了C語言中strcmp的實現(xiàn)原型的相關資料,這里提供實例幫助大家理解這部分內(nèi)容,希望能幫助到大家,需要的朋友可以參考下
    2017-08-08

最新評論

甘南县| 岳阳县| 农安县| 轮台县| 卓资县| 扎兰屯市| 桐柏县| 虞城县| 泉州市| 海淀区| 青州市| 镇安县| 通辽市| 安陆市| 天镇县| 大足县| 田阳县| 元阳县| 大理市| 高安市| 德令哈市| 鱼台县| 兴山县| 织金县| 嘉定区| 长丰县| 慈利县| 乌鲁木齐县| 泸溪县| 濉溪县| 永善县| 寿光市| 永安市| 上虞市| 东辽县| 项城市| 肥东县| 忻州市| 九龙城区| 醴陵市| 巫山县|