How to catch exception in the main thread if the exception occurs in the secondary thread?
The code snippet for the scenario is given below:
private void button1_Click(object sender, EventArgs e)
{
try
{
Thread th1 = new Thread(new ThreadStart(Test));
th1.Start();
}
catch (Exception)
{
}
}
void Test()
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
if (i == 2)
throw new MyException();
}
}
You can add a Application.ThreadException Event handler:
Joe is correct. Given the above windows forms code I was assuming Windows forms:
This event allows your Windows Forms application to handle otherwise unhandled exceptions that occur in Windows Forms threads. Attach your event handlers to the ThreadException event to deal with these exceptions, which will leave your application in an unknown state. Where possible, exceptions should be handled by a structured exception handling block.
See Unexpected Errors in Managed Applications
Use a BackgroundWorker.
A BackgroundWorker provides the infrastructure for communicating between the main UI thread and a background worker thread, including reporting exceptions. It is almost always a better solution than starting a thread from a button_click event handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With