Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Throw exception without breaking the loop

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?

like image 365
noobie Avatar asked Mar 27 '13 07:03

noobie


2 Answers

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
like image 128
JleruOHeP Avatar answered Sep 22 '22 02:09

JleruOHeP


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

like image 39
Tomtom Avatar answered Sep 24 '22 02:09

Tomtom