[英]how to continue a foreach loop
我在下面有for每個循環,想知道在引發異常后如何繼續執行此操作,以便將其轉到下一個下一個數組索引,並且系統不會失敗。
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
}
理想情況下,我會盡量避免所有例外情況。 在您的情況下,您可以在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.
}
}
您不能,因為異常而爆發,而是在循環內移動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
}
}
將您的try-catch語句放入循環,並在catch塊中使用Continue關鍵字。
將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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.