如何抛出异常并继续循环(或如何从一个循环中抛出许多异常)

Hur*_*ane 1 c# exception-handling exception

我有两个方法,对我来说需要从一个到另一个生成异常,就像这样

public void Method1()
{ 
    try
    {  
        Method2(1);
    }
    catch(Exception e )
    {
        SendEmail (/* some message */)
    }
}

public IEnumerable<int> Method2(int id)
{
    foreach (var i in col)
    {
        try
        { 
            /*Do some stuff*/ 
            yield return i 
        }
       catch
       {
           /* delegate this exception to Method1 and continue foreach loop */
       }            
    }
 }
Run Code Online (Sandbox Code Playgroud)

如何将方法2中的异常委托给方法1并继续方法2中的foreach循环

UPD:

那怎么样?

例如:方法1 - >方法3 - >方法2 - >方法2在方法1中返回异常

UPD2:到UPD

   /*Call*/
        var i = new List<int>() {0, 0, 0, 0, 0, 0, 7, 0, 9};
        Calc(i, SendMessage);


   public static void SendMessage(Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }

    public static double Calc(List<int> list, Action<Exception> callback)
    {
        var a = 0.00;
        foreach (var i in list)
        {
            try
            {
                a = Calc1(i);/*if here (double)7 / i it's just works but in how to include in method*/
            }
            catch (Exception ex)
            {
                callback(ex);
            }
        }
        return a;
    }

    public static double Calc1(int i)
    {
        var a = 0.00;
        a = (double)7 / i;
        return a;
    }
Run Code Online (Sandbox Code Playgroud)

kha*_*kha 8

  1. 你不能在yield return里面尝试/捕获.
  2. 你可以这样做,如果你真的想这样做,但我不是真的推荐这种方法.应该在他们抛出的时间和地点处理异常,或者在我看来应该重新抛出异常.

    public void Method1()
    {
        Method2(1, ex => SendEmail(ex));
    }
    
    public IEnumerable<int> Method2(int id, Action<Exception> callback)
    {
        foreach (var i in new List<int>())
        {
            try
            {
                /*Do some stuff*/
            }
            catch(Exception ex)
            {
                callback(ex);
            }
    
            yield return i;
        }
    }
    
    private void SendEmail(Exception ex)
    {
        // blah
    }
    
    Run Code Online (Sandbox Code Playgroud)