1

I try to catch exceptions from another thread, but can't.

static void Main(string[] args)
{
    try
    {
        Task task = new Task(Work);
        task.Start();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }

    Console.WriteLine();
}

public static void Work()
{
    throw new NotImplementedException();
}

I write try-catch and at method too, but nothing happens. Please,tell me how to know that exception throw?

Maybe you could show me some example code.

Filburt
  • 17,626
  • 12
  • 64
  • 115
user2545071
  • 1,408
  • 2
  • 24
  • 46

4 Answers4

1

Your code may not raise the exception as the main method will executes too fast and the process will terminate before you got the exception

Here how it would look your code

static void Main(string[] args)
        {

                Task task = new Task(Work);
                task.Start();
            var taskErrorHandler = task.ContinueWith(task1 =>
                {


                    var ex = task1.Exception; 

                    Console.WriteLine(ex.InnerException.Message);


                }, TaskContinuationOptions.OnlyOnFaulted);

            //here you  should put the readline in order to avoid the fast execution  of your main thread
            Console.ReadLine(); 
        }

        public static void Work()
        {
            throw new NotImplementedException();
        }

Try to take a look at ContinueWith

BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47
0

The OnlyOnFaulted member of the TaskContinuationOptions enumeration indicates that the continuation should only be executed if the antecedent task threw an exception.

task.ContinueWith((Sender) =>
    {
        ////This will be called when error occures
        Sender.Result
    }, TaskContinuationOptions.OnlyOnFaulted);
Neel
  • 11,625
  • 3
  • 43
  • 61
0

Your try/catch wouldn't work. For one reason : because you could very well have gone out of the try block before the exception is thrown, as the Task is done on another thread.

With a Task, there are two ways to get the exceptions.

The first one is to use task.Wait(); in your try block. This method will rethrow any exception thrown by the task. Then, any exception will be handled on the calling thread in the catch block.

The second one is to use the ContinueWith method. This won't block your calling thread.

task.ContinueWith(t => 
{
    // Here is your exception :
    DoSomethingWithYour(t.Exception);
}, TaskContinuationOptions.OnlyOnFaulted);
krimog
  • 1,257
  • 11
  • 25
-1

Note the following will block the main thread since Wait is employed.

try
{
    Task task = Task.Factory.StartNew(Work);
    task.Wait();
}
catch (AggregateException ex)
{
    Console.WriteLine(ex.ToString());
}
daryal
  • 14,643
  • 4
  • 38
  • 54