非同期例外
以下のコードは、別のスレッドで発生した例外を処理します。
// exception1.cpp
#include <functional>
#include <exception>
#include <iostream>
#include <stdexcept>
#include <thread>
using namespace std;
void thrower(exception_ptr & p) {
try {
throw runtime_error("throwed");
}
catch(...) {
p = current_exception();
}
}
int main(int, char *[]) {
exception_ptr e;
thread t(thrower, ref(e));
t.join();
try {
if(e != exception_ptr()) rethrow_exception(e);
} catch(const exception & x) {
cout << x.what() << endl;
}
return 0;
}
current_exception で初期化された exception_ptr の内容は唯一なので、rethrow_exception を通して元スレッド内で再スローします。
© 2012 Gallonworks

