C#如果方法失败(Catch),DoSomething

时间:2011-12-06 11:28:38

标签: c# if-statement try-catch

想象一下,你有一个方法:

public void SometimesIFail(string text)
{
    bool everythingOk = true;
    try
    {
         //Anything
    }
    catch(Exception)
    {
         //Anything
         everythingOk = false
    }


}

现在我想做那样的事情:

    foreach (String text in texts)
    {
        if(!SometimesIFail(text)) //If SometimesIFail() Failed (walked into Catch) Do the same for the next TEXT from the List: texts
        {
            SometimesIFail(text); // The Next Text - Until iterated through all the texts..
            //FROM HERE ON, I HAVE A RECURSIVE CALL, THAT MEANS THAT THIS CODE, MUSTNT BE EXECUTED 
            //Any Code..
        } 
        else
        {
            //Do Something
        }
    }

解决问题的最佳方法是什么?

编辑:

测试结束后(检查是否正常),我想做点什么,当它不行时,

foreach (String text in texts)
{
     if(!SometimesIFail(text)) 
     {
           //HERE I will do SometimesIFail(text) for the next text (in foreach)

           // And here is a Recursive Call which should be called, after the foreach iterated through all the texts..
     } 
 }

4 个答案:

答案 0 :(得分:3)

让异常尽可能地冒泡。因此,从SometimesIFail方法中删除try / catch,并将错误更接近用户。像这样:

try {
    SometimesIFail();
    // Do stuff 
} catch {
    // Tell the user an error has occurred.
}

并考虑所谓的例外情况 - 它们是例外,不应该用于流量控制。如果您的代码出现问题导致其有时崩溃,请改为解决问题。

答案 1 :(得分:1)

我认为如果你解决了问题,不试试,那么这将是更好的选择......

答案 2 :(得分:0)

尝试使用:

public bool SometimesIFail(string text) 
{ 
    try 
    { 
         //Anything
         return false;
    } 
    catch(Exception) 
    { 
         //Anything
         return true;
    } 
}

foreach (String text in texts)  
{  
    SometimesIFail(text);  
    if(SometimesIFail(text)) 
    { 
        // returned true - exception was thrown
        SometimesIFail(text);
    }   
    else  
    {  
        //Do Something  
    }  
}  

答案 3 :(得分:0)

起初我以为我知道你在找什么,然后我读了代码片段中的评论,所以现在我不太确定。根据我的想法,这是我的答案。看起来你想要检查SometimesIFail方法是否成功,如果成功执行了一些代码,如果失败则你想继续下一次迭代。以下是我将为该场景做的事情:

// Don't use a void here, use a bool
public bool SometimesIFail(string text)
{
    try
    {
         //Anything
         return true;
    }
    catch(Exception)
    {
         //Anything
         return false;
    }
}

...

foreach (String text in texts)
{
    if(SometimesIFail(text)) // Evaluates to true for success
    {
        // Do your success matching code
    }

    // There doesn't need to be an else condition if you're
    // only passing to the next iteration
}