C ++:如何从线程中捕获异常

时间:2018-11-21 02:09:56

标签: c++ multithreading c++11 exception

我正在尝试从外部捕获线程异常,但是我不能,这是我的代码:

#include <iostream>
#include <thread>
#include <chrono>

void func1()
{
    while (true)
    {
        std::cout<<"thread 1"<<std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(2000));
    }
}

void func2()
{
    int i = 0;
    while (true)
    {
        std::cout<<"thread 2"<<std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(2000));
        if (i++ == 3)
        {
            throw 1;
        }
    }
}

int main()
{
    try{
    std::thread t1(func1);
    std::thread t2(func2);
    t2.join();
    t1.join();
    }catch(int e){
        std::cout<<"exception catched!"<<std::endl;
    }
    std::cout<<"main end"<<std::endl;
    return 0;
}

但是,我立即丢弃了一个内核,似乎没有发现异常:

thread 1
thread 2
thread 1
thread 2
thread 1
thread 2
thread 1
thread 2
thread 1
terminate called after throwing an instance of 'int'
Aborted (core dumped)

0 个答案:

没有答案