0

基于如何在线程之间传播异常?,我创建了一个小测试应用程序来探索传播:

#include <vcl.h>
#pragma hdrstop

#include<iostream>
#include<thread>
#include<exception>
#include<stdexcept>
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;

static std::exception_ptr teptr = nullptr;
static UnicodeString status;

void __fastcall f()
{
    try
    {
        throw std::runtime_error("To be passed between threads");
    } catch(...) {
        teptr = std::current_exception();
        if (!teptr) {
            status += U"; NULL teptr";
        } else {
            status += U"; Non-NULL teptr";
        }
    }
}

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    std::thread mythread(f);
    mythread.join();

    std::this_thread::sleep_for(std::chrono::seconds(3));

    if (teptr) {
        status += U"; Button1Click non-NULL teptr";
        try
        {
            std::rethrow_exception(teptr);
        } catch(const std::exception &ex) {
            std::cerr << L"Thread exited with exception: " << ex.what() << "\n";
        }
    } else {
        status += U"; Button1Click NULL teptr";
    }
    Application->MessageBox(status.c_str(), L"Button1Click", MB_OK);
}

消息框中的结果是"; NULL teptr; Button1Click NULL teptr",所以对我来说,它似乎std::current_exception()无法正常工作。如何让应用程序抛出的错误传播回启动线程的程序?

4

0 回答 0