Question

For example:

 try
{
   Task1();
   Task2();
   Task3();
}
catch (Exception ex)
{
}

Right now if an exception occurs in Task1(), the code in Task2 and Task2 method does not run. The program stops.

How could I make it so when an exception occurs, the code / methods that below it would keep on running to the end.

Thanks

Was it helpful?

Solution

An exception moves execution to the end of the try block and into the catch block. To do what you want, you'd have to use separate try/catch blocks:

try
{
   Task1();
}
catch (Exception ex)
{
}

try
{
   Task2();
}
catch (Exception ex)
{
}

try
{
   Task3();
}
catch (Exception ex)
{
}

You could put your tasks in a collection (provided they all have the same signature) and loop, but the net effect would be the same:

var tasks = new Action[] {Task1, Task2, Task3};
foreach(var task in tasks)
{
    try
    {
       task();
    }
    catch (Exception ex)
    {
    }
}

OTHER TIPS

Currently, in the code that you have, if there is an exception throw trying to start Task1() then the other two tasks are not started. If that task is started without error but results in a task that is in a Faulted state, then your other tasks are properly started.

Generally one would not expect methods like these to throw an exception starting the task in most situations. Null checking arguments is something commonly done, but other than that one would generally expect such methods to not fail to start the task. If you have any control over the method, consider re-designing it so that it generates a faulted task instead of throwing an exception, unless you have a good reason to do otherwise.

You may also want to create a method that takes a task-returning method and, if it fails to generate a task, instead creates a faulted task. If it is successful, it can just return that task:

public static Task WrapExceptions(this Func<Task> function)
{
    try
    {
        return function();
    }
    catch (Exception e)
    {
        var tcs = new TaskCompletionSource<bool>();
        tcs.SetException(e);
        return tcs.Task;
    }
}

If you want to ensure all tasks are started even if there is an exception when starting the task, then you need to wrap each method call in its own try/catch.

Put each statement in its own try-catch block:

try
{
   Task1();
}
catch (Exception ex)
{
}
try {
   Task2();
}
catch (Exception ex)
{
}
try {
   Task3();
}
catch (Exception ex)
{
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top