【问题标题】:How to resume second method after first method throws an exception C#第一种方法引发异常后如何恢复第二种方法C#
【发布时间】:2023-03-16 04:00:01
【问题描述】:

在查看 C# try catch 教程时,我遇到了以下问题。我的示例代码如下,

mainMethod() 内部,我需要调用三个单独的方法。在testMethodOne() 内部,我需要处理异常。如果testMethodOne()抛出异常,不执行testMethodTwo(dt)mainMethod()抛出异常。如果testMethodOne() 抛出异常,我需要调用testMethodTwo(dt);testMethodThreee(dt);,我该怎么做。

public void MainMethod(data dt){

    try{
    
    testMethodOne(dt);
    testMethodTwo(dt);
    testMethodThreee(dt);   
    
    }catch(Exception ex){
    
    
        throw ex;
    
    }
}

public void testMethodOne(dt){
    try 
    {
      //  Block of code to try
    }
    catch (Exception e)
    {
      //  Block of code to handle errors
    }
} 

【问题讨论】:

    标签: c# exception try-catch


    【解决方案1】:

    我对你的问题理解如下(但我可能错了,你的问题不是很清楚):

    即使您的一个 testMethods 抛出异常,您仍然希望使用其他方法继续正常的程序流程。如果至少有一个方法失败,mainMethod 可以将其报告为AggregateException

    public void MainMethod(data dt)
    {
        var exceptions = new List<Exception>();
    
        try
        {
            testMethodOne(dt);
        }
        catch (Exception ex)
        {
            exceptions.Add(ex);
        }
    
        try
        {
            testMethodTwo(dt);
        }
        catch (Exception ex)
        {
            exceptions.Add(ex);
        }
    
        try
        {
            testMethodThreee(dt);   
        }
        catch (Exception ex)
        {
            exceptions.Add(ex);
        }
    
        if (exceptions.Count > 0)
        {
            throw new AggregateException(exceptions);
        }
    }
    

    【讨论】:

      【解决方案2】:

      似乎您希望异常来改变您的主要方法的流程而不破坏一切。一种简单的方法是让每个 'testmethod' 返回一个布尔值。

      public bool testMethodOne(dt){
          try 
          {
            //  Block of code to try
            return true;
          }
          catch (Exception e)
          {
            //  Block of code to handle errors
            return false;
          }
      } 
      

      然后在你的主代码中你可以去

      if(!testMethodOne(dt))
          if(!testMethodTwo(dt))
              if(!testMethodThree(dt)) 
                   //log that all methods failed
      

      上面的 sn-p 会尝试每个方法,直到找到一个成功的方法。如果这不是您正在寻找的行为,您可以改写您的问题以使其更清楚吗?如果您希望发生相反的情况,只需摆脱 !它会一直持续到失败。或者,您可以在每个 testMethods 中的 catch 语句中添加一个 throw,一旦达到一个,它也会停止执行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-17
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        相关资源
        最近更新 更多