物理の駅 Physics station by 現役研究者

テクノロジーは共有されてこそ栄える

マルチスレッドにおける例外処理の受け渡し (VC++)

別スレッド中の例外を、本スレッドに渡す方法のメモ。動作確認はVisual Studio 2013 C++で行っている。

詳しい説明は スレッド間の例外転送 を参照してね。

#include <thread>
#include <iostream>

//マルチスレッド用の関数
void f1(std::exception_ptr &eptr) {
    try {
        throw std::exception("test");
    }
    catch (...) { //すべての例外を受ける
        eptr = std::current_exception();
    }
}

int main() {
    std::exception_ptr eptr;
    std::thread t1(f1, std::ref(eptr)); //スレッドを作成し参照でeptrを渡す
    t1.join(); //終了待ち

    try {
        if (eptr) {
            std::rethrow_exception(eptr); //例外を投げなおす
        }
    }
    catch (std::exception &ex) {
        std::cout << ex.what() << std::endl;
    }
    ::system("pause"); //デバッグ用のpause
}