Search code examples
c#exceptioncontinue

After an exception, keep on running


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


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)
        {
        }
    }