欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

本文講述如何利用v8::TryCatch捕捉j(luò)s代碼中發(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 );
}

設(shè)置訪問器訪問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的結(jié)果沒有繼續(xù)調(diào)用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();

運行結(jié)果:

總結(jié)

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

相關(guān)文章

  • C++基于boost asio實現(xiàn)sync tcp server通信流程詳解

    C++基于boost asio實現(xiàn)sync tcp server通信流程詳解

    這篇文章主要介紹了C++基于boost asio實現(xiàn)sync tcp server通信的流程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07
  • QT實現(xiàn)動態(tài)時鐘

    QT實現(xiàn)動態(tài)時鐘

    這篇文章主要為大家詳細(xì)介紹了QT實現(xiàn)動態(tài)時鐘,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-07-07
  • C與C++ 無參函數(shù)的區(qū)別解析

    C與C++ 無參函數(shù)的區(qū)別解析

    在《C++ 編程思想》:“關(guān)于無參函數(shù)聲明,C與C++有很大的差別。在C語言中,聲明int fun1(),意味著一個可以有任意數(shù)目和類型的函數(shù);而在C++中,指的卻是一個沒有參數(shù)的函數(shù)”
    2013-07-07
  • 詳解C++ 運算符重載中返回值的坑

    詳解C++ 運算符重載中返回值的坑

    這篇文章主要介紹了C++ 運算符重載中返回值的坑,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • C語言中查找字符在字符串中出現(xiàn)的位置的方法

    C語言中查找字符在字符串中出現(xiàn)的位置的方法

    這篇文章主要介紹了C語言中查找字符在字符串中出現(xiàn)的位置的方法,分別是strchr()函數(shù)和strrchr()函數(shù)的使用,需要的朋友可以參考下
    2015-08-08
  • C語言實現(xiàn)小貓釣魚算法

    C語言實現(xiàn)小貓釣魚算法

    這篇文章主要為大家詳細(xì)介紹了C語言實現(xiàn)小貓釣魚算法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • C++實現(xiàn)圖書館系統(tǒng)

    C++實現(xiàn)圖書館系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了C++實現(xiàn)圖書館系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • C++使用chrono庫處理日期和時間的實現(xiàn)方法

    C++使用chrono庫處理日期和時間的實現(xiàn)方法

    C++11 中提供了日期和時間相關(guān)的庫 chrono,通過 chrono 庫可以很方便地處理日期和時間,本文主要介紹了C++使用chrono庫處理日期和時間的實現(xiàn)方法,感興趣的小伙伴們可以參考一下
    2021-09-09
  • C++中Boost的智能指針shared_ptr

    C++中Boost的智能指針shared_ptr

    這篇文章介紹了C++中Boost的智能指針shared_ptr,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-07-07
  • c語言打開文件函數(shù)使用方法

    c語言打開文件函數(shù)使用方法

    這篇文章主要介紹了c語言打開文件函數(shù)使用方法,需要的朋友可以參考下
    2014-02-02

最新評論