Search code examples
c#exceptiontry-catchexecutethrow

C# How do i resume the execution of my code after a catch?


Is it possible to resume the execution of my Programm after the first catch even if i throwed the exception?

I made an example programm but the line where i added the exception to my List<string> has to be executed exactly after the inner and inside the outer foreach i know it would be possible if i wouldnt throw the exception but i have to do this aswell.

foreach(var x in x)
{
    try
    {
        List<string> exs = new List<string>();
        foreach(var a in b)
        {
            try
            {
                //...some code
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                //...some code
            }
        }
        exs.Add(ex);
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex);
    }
    finally
    {
        //...some code
    }
}

Solution

  • Don't throw them, but collect and print them later.

    List<Exception> exs = new List<Exception>();
    try
    {
    
        foreach(var a in b)
        {
            try
            {
                //...some code
            }
            catch(Exception ex)
            {
                exs.Add(ex);
            }
            finally
            {
                //...some code
            }
        }        
    }    
    catch(Exception e)
    {
       Console.WriteLine(e.ToString());
    }
    finally
    {
        //...some code
    }
    exs.ForEach(ex=> Console.WriteLine(ex.ToString()));