Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continue the foreach in try and catch?

Tags:

c#

.net

If I catch an exception during execution of a foreach, can I continue execution?

foreach (string d in Directory.GetDirectories(path))
    {
        try
        {
            foreach (string f in Directory.GetFiles(path))
            {
                //do something
            }
            //do something
        }
        catch
        {
           // If there is an error in the foreach, I want it to keep on going
        }
    }

I am asking this because it suddenly terminates before the foreach gets all the files.

like image 638
newbie Avatar asked Oct 07 '12 03:10

newbie


2 Answers

Simply do:

foreach (string d in Directory.GetDirectories(path))
{
        foreach (string f in Directory.GetFiles(path))
        {
            try
            {
                //do some thing
            }
            catch
            {
               // If there is an error on the foreach, I want it to keep on going to search another one
            }
        }
        //do some thing
}
like image 106
Sidharth Mudgal Avatar answered Sep 19 '22 11:09

Sidharth Mudgal


foreach (string d in Directory.GetDirectories(path)) {
    foreach (string f in Directory.GetFiles(path)) {
        try {
            //do some thing
        } catch { /* log an error */ }
    }

    try {
        //do some thing
    } catch { /* log an error */ }
}
like image 25
cdhowie Avatar answered Sep 18 '22 11:09

cdhowie