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?
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
You have to build a try-catch-block inside your loop and don't throw the exception again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With