Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching exceptions caused in different threads [duplicate]

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());
        }
like image 853
CathalMF Avatar asked Jan 14 '23 01:01

CathalMF


1 Answers

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.

like image 189
Matthew Watson Avatar answered Jan 22 '23 19:01

Matthew Watson