catch 節の中で関数を呼び出すと、その関数の中で呼び出し元で catch していた例外を受け取れるというもの。
//<tips> 例外処理を関数にまとめる try{ throw; } #include <iostream> #include <string> #include <exception> void report_exception() { std::string err("exception: "); try{ throw; } //※ catch(std::exception& ex) { err+= ex.what(); } //catch(xxx)...と続く std::cerr << err << std::endl; } int main(int, char *[]) { try { throw std::logic_error("test exception"); } catch(...) { report_exception(); } return 0; }
こんなやり方があるのか……。これが使えると try-catch で関数が長くなってしまうこともないでしょうし、同じコード(例外処理)をあちこちに書かずにまとめられてとても良さそうですね。
なお今回からソースが色分けされていますが、これには p_stade; さんで公開されていた cpp2hatena のソースを使用させて貰いました。実際見つけたのは随分前(ブクマを見ると9月4日)なんですが、 boost をビルドするのが億劫でなかなか試せなかったのです。せっかくなので、ソースも読んで理解したいなあ。 boost::spirit の勉強のために。