boost 异常监控库 (RobinKin 整理)

此博客给出一段C++代码,包含结构体定义、异常处理等内容。定义了my_exception1和my_exception2结构体,dangerous_call_monitor类用于监控操作并抛出异常,还实现了异常翻译函数,最后在main函数中进行异常处理,同时给出编译方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//file name  : mon.cpp
#include <boost/test/execution_monitor.hpp>

#include <iostream>

struct my_exception1
{
    explicit    my_exception1( int res_code ) : m_res_code( res_code ) {}

    int         m_res_code;
};

struct my_exception2
{
    explicit    my_exception2( int res_code ) : m_res_code( res_code ) {}

    int         m_res_code;
};

struct dangerous_call_monitor : boost::execution_monitor
{
    explicit dangerous_call_monitor( int argc ) : m_argc( argc ) {}

    virtual int function()
    {
        // here we perform some operation under monitoring that could throw my_exception
        if( m_argc < 2 )
            throw my_exception1( 23 );
        if( m_argc > 3 )
            throw my_exception2( 45 );
        else if( m_argc > 2 )
            throw "too many args";

        return 1;
    }

    int m_argc;
};

void translate_my_exception1( my_exception1 const& ex )
{
    std::cout << "Caught my_exception1(" << ex.m_res_code << ")"<<
std::endl; 
}

void translate_my_exception2( my_exception2 const& ex )
{
    std::cout << "Caught my_exception2(" << ex.m_res_code << ")"<<
std::endl; 
}

int cpp_main( int argc , char *[] )
{
}

int
main( int argc , char *[] )
{
    dangerous_call_monitor the_monitor( argc );

    the_monitor.register_exception_translator<my_exception1>(
&translate_my_exception1 );
    the_monitor.register_exception_translator<my_exception2>(
&translate_my_exception2 );

    try {
        the_monitor.execute();
    }
    catch ( boost::execution_exception const& ex ) {
        std::cout << "Caught exception: " << ex.what() << std::endl;
    }

    return 0;
}

// EOF

编译方式 : g++ -o mon -lboost-prt-exec-monitor-gcc mon.cpp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值