Based on the credited answer to How can I propagate exceptions between threads?, I created a little test application to explore propagation:
#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);
}
The results in the message box turn out to be "; NULL teptr; Button1Click NULL teptr"
, so to me, it looks like std::current_exception()
failed to work. How can I get an application-thrown error to propagate back to the program that launched the thread?