C# Throw exception without breaking the loop

14,323

Solution 1

No, you can`t throw an exception from the loop and continue to iterate throught it. However you can save your exception in the array and handle them after the loop. Like this:

List<Exception> loopExceptions = new List<Exception>();
foreach (var item in itemList)
  try 
  {
    //do something
  }
  catch (Exception ex)
  {
    loopExceptions.Add(ex);
  }

foreach (var ex in loopExceptions)
  //handle them

Solution 2

You have to build a try-catch-block inside your loop and don't throw the exception again.

Share:
14,323
noobie
Author by

noobie

Updated on June 23, 2022

Comments

  • noobie
    noobie almost 2 years
    void function() {
        try
        {
            // do something
    
            foreach (item in itemList)
            {
                try 
                {
                    //do something
                }
                catch (Exception ex)
                {
                    throw new Exception("functionB: " + ex.Message);
                }
            }
        }
        catch (Exception ex)
        {
            LogTransaction(ex.Message);
        }
    }
    

    Hi, I would like to throw the exception from the for loop to its parent. Currently when there is an exception in the for loop, the loop will be terminated. Is there anyway to modify it so that the exception will be thrown but the loop will continue?