I have heard from a very discerning person that an exception being thrown (and not caught) in a thread is being propagated to the parent thread. Is that true? I have tried something like this but couldn't catch the exception in the creating thread.
static void Main(string[] args)
{
ParameterizedThreadStart pts =
new ParameterizedThreadStart(ThreadMethod);
try
{
Thread t = new Thread(pts);
t.Start(new object());
Console.ReadLine();
}
catch (Exception ex) //the exception is not caught
{
Debugger.Break();
}
}
static void ThreadMethod(object @object)
{
Thread.Sleep(2000);
throw new IndexOutOfRangeException();
Thread.CurrentThread.Abort();
}
The thread's exception will not propogate to the main thread's context. This really makes sense - by the time the exception is thrown, the main thread will typically be in a completely different scope than the one containing your exception handler.
You can catch these exceptions (typically to log them) by hooking into AppDomain.UnhandledException. See that page for details, including differences in Windows Forms applications, etc.
This is a great article about Threading in C# and how to handle Exceptions
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