如何继续foreach循环

时间:2013-08-28 10:25:48

标签: c# foreach

我有下面的每个循环,并且想知道在抛出异常之后我将如何能够继续这个,以便它进入下一个下一个数组索引,并且系统不会失败。

try
{
//making name array and other checks 
    foreach (string s in namearry)
    {
        var timelineData = oAuthTwitterWrapper.GetMyTimeline(s);
        TwitterData.TimeLineData(timelineData, s, int.Parse(dr["ClientId"].ToString()));
        //  var followersId = oAuthTwitterWrapper.GetFolowersId(s);
        // var loc = oAuthTwitterWrapper.GetFolowersLoc(followersId);
        //  TwitterData.Follower(loc, s);
    }
}
catch(Exception ex)
{
    //logging exception 
}

4 个答案:

答案 0 :(得分:3)

理想情况下,我会尽量避免所有例外情况。在您的情况下,您可以在foreach循环中处理异常。在以下示例中,我添加了必要的检查以避免首先发生异常。像这样

foreach (string s in namearry)
{
    try
    {
        var timelineData = oAuthTwitterWrapper.GetMyTimeline(s);
        if(timelineData!=null)
        {
             int clientID;
             if(int.TryParse(dr["ClientId"].ToString(), out clientID))
             {
                  TwitterData.TimeLineData(timelineData, s, clientID);            
             }
        }
    }
    catch(Exception exp)
    {
        //do logging here.
    }
}

答案 1 :(得分:1)

你不能,你发现异常,而是在循环中移动try / catch。

foreach (string s in namearry)
{
    try {
        //making name array and other checks 
        var timelineData = oAuthTwitterWrapper.GetMyTimeline(s);
        TwitterData.TimeLineData(timelineData, s, int.Parse(dr["ClientId"].ToString()));
        //  var followersId = oAuthTwitterWrapper.GetFolowersId(s);
        // var loc = oAuthTwitterWrapper.GetFolowersLoc(followersId);
        //  TwitterData.Follower(loc, s);
    }
    catch(Exception ex) {
        //logging exception 
    }
}

答案 2 :(得分:0)

try-catch 语句放入循环中,并使用catch块中的 continue 关键字。

答案 3 :(得分:0)

try 放在的foreach中,而不是在外面。 或者,如果你在外面需要它,那么在里面放另一个,处理异常。

try{
//making name array and other checks, that may trigger exceptions
    foreach (string s in namearry)
    {
        try
        {
            var timelineData = oAuthTwitterWrapper.GetMyTimeline(s);
            TwitterData.TimeLineData(timelineData, s, int.Parse(dr["ClientId"].ToString()));
            //  var followersId = oAuthTwitterWrapper.GetFolowersId(s);
            // var loc = oAuthTwitterWrapper.GetFolowersLoc(followersId);
            //  TwitterData.Follower(loc, s);
        }
        catch(Exception ex)
        {
            //logging exception: this will override the outer handler, which will not be called.
        }
    }
}
catch(Exception ex){
    //logging exception
    //exceptions raised before entering the foreach are handled here
}