Boost 的 execution_monitor 提供了一套異常監控機制,能攔截程式執行過程中所拋出的自訂例外,並交由使用者註冊的翻譯函式來處理。以下是一個完整範例:
//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()
{
// 在此進行一段受監控、可能丟出例外的操作
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
程式的關鍵在於:自訂的 dangerous_call_monitor 繼承自 boost::execution_monitor,並在其 function() 中依參數數量丟出不同的例外;接著透過 register_exception_translator 註冊對應的翻譯函式,就能把例外攔截下來並輸出友善的訊息。這樣的設計讓例外處理的邏輯得以集中管理,相當適合用在需要嚴謹監控的關鍵流程。