The below example is a simplification of my problem. An exception is thrown within a new thread. If im not handling this within the thread it is not caught by the outer try/catch and crashes my application.
Is there any way to guarantee that I catch any exception that occurs.
try
{
new Thread(delegate()
{
throw new Exception("Bleh"); // <--- This is not caught
}).Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Generally speaking, it's easiest to catch the exceptions within the thread itself.
But if you want to catch the exception separately from the thread function itself (and if you can use Task
instead of the old Thread
approach), you can write code like this:
var task = Task.Factory.StartNew(() =>
{
throw new Exception("Test");
});
task.ContinueWith(t => handleException(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
This uses ContinueWith()
to call another method after the first thread has finished and an exception occurred, so you can log the exception or whatever:
static void handleException(AggregateException exception)
{
foreach (var ex in exception.Flatten().InnerExceptions)
Console.WriteLine(ex.Message);
}
This doesn't really let you fix anything up - the only sensible way to do that is to handle the exceptions properly in the thread function itself.
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