function try block?
ネタ元
Ruby on Rails application could not be started
Ruby on Rails application could not be started
#include <iostream> #include <stdexcept> #include <boost/lexical_cast.hpp> using namespace std; using namespace boost; #define d(str) (cout << str << " @ " << __func__ << endl) class Bar { public: Bar(int n) { d("ctor. [" + lexical_cast<string>(n) + "]"); if (!n) throw domain_error("Bar!!! [" + lexical_cast<string>(n) + "]"); } }; class Foo { public: Foo(int i, int j) try : bar(i), hoge(j) { d("ctor. "); } catch (const exception& e) { d(e.what()); } private: Bar bar, hoge; }; int main(void) { try { Foo(1, 0); } catch (const exception& e) { d(e.what()); } return 0; }
astyle で整形したら若干崩れてる。
こんな構文知らなかったなぁ。しかも、この構文上でキャッチした例外は rethrow される、と。
hoge の初期化時に例外が飛んで構築に失敗してるんだから、それを持ってるクラスが構築に成功したらダメって事かな。
以下、実行結果。見事に rethrow されている。
% g++ -Wall function_try_block.cpp % ./a.out ctor. [1] @ Bar ctor. [0] @ Bar Bar!!! [0] @ Foo Bar!!! [0] @ main