我已經實現了一個繼承boost :: statechart的狀態機。當我打電話給fsm.process_event(some_event())
哪個反應預計會拋出異常時,事實證明,在我用try-catch塊處理異常之後,我的statemachine實例fsm
被終止。即,fsm.terminated()
返回true
。在某些情況下,我不希望它終止。就像我希望狀態機拋出異常,通知調用者fsm.process_event(irrelevant_event())
未處理事件並在事件狀態之前保持其當前狀態。如何防止boost :: statetechart因拋出異常而終止
總之 - 我怎樣才能防止boost::statechart
在引發異常並在異常狀態之前保持其終止之後終止?
示例代碼:
namespace sc = boost::statechart;
class State;
struct some_event : public sc::event<some_event> { };
class FSM
: public sc::state_machine< FSM, State, std::allocator<void>, sc::exception_translator<> >
{
public:
FSM()
{
cout<<"FSM::FSM()"<<endl;
}
virtual ~FSM()
{
cout<<"FSM::~FSM()"<<endl;
}
};
class State : public sc::simple_state< State, FSM >
{
public:
State()
{
cout<<"State::State()"<<endl;
}
virtual ~State()
{
cout<<"State::~State()"<<endl;
}
typedef boost::mpl::list<
sc::custom_reaction<some_event>,
sc::custom_reaction<sc::exception_thrown>
> reactions;
sc::result react(const some_event & e)
{
cout<<"State::react(const some_event &)"<<endl;
throw std::exception();
return this->discard_event();
}
sc::result react(const sc::exception_thrown & e)
{
cout<<"State::react(const sc::exception_thrown &)"<<endl;
throw;
return this->discard_event();
}
};
int main()
{
FSM fsm;
fsm.initiate();
try
{
fsm.process_event(some_event());
}
catch(...)
{
cout<<"Exception caught"<<endl;
}
if(fsm.terminated())
{
cout<<"fsm2 is TERMINATED"<<endl;
}
else
{
cout<<"fsm2 is RUNNING"<<endl;
}
return 0;
}
代碼輸出:
FSM::FSM()
State::State()
State::react(const some_event &)
State::react(const sc::exception_thrown &)
State::~State()
Exception caught
fsm2 is TERMINATED
我希望它輸出:
FSM::FSM()
State::State()
State::react(const some_event &)
State::react(const sc::exception_thrown &)
State::~State()
Exception caught
fsm2 is RUNNING