2012-12-28 53 views
1

我有一個多播委託,我通過它調用兩種方法。如果第一個方法中存在異常並且它處理了,那麼如何繼續執行第二個方法調用?我附上下面的代碼。在下面的代碼中,第一個方法拋出異常。但我想知道如何通過多播委託調用繼續執行第二種方法。內環路多播委託中的異常處理

public delegate void TheMulticastDelegate(int x,int y); 
    class Program 
    { 
      private static void MultiCastDelMethod(int x, int y) 
      { 
        try 
        { 
          int zero = 0; 
          int z = (x/y)/zero; 
        } 
        catch (Exception ex) 
        {        
          throw ex; 
        } 
      } 

      private static void MultiCastDelMethod2(int x, int y) 
      { 
        try 
        { 
          int z = x/y; 
          Console.WriteLine(z); 
        } 
        catch (Exception ex) 
        { 
          throw ex; 
        } 
      } 
      public static void Main(string[] args) 
      { 
        TheMulticastDelegate multiCastDelegate = new TheMulticastDelegate(MultiCastDelMethod); 
        TheMulticastDelegate multiCastDelegate2 = new TheMulticastDelegate(MultiCastDelMethod2); 

        try 
        { 
          TheMulticastDelegate addition = multiCastDelegate + multiCastDelegate2; 

          foreach (TheMulticastDelegate multiCastDel in addition.GetInvocationList()) 
          { 
            multiCastDel(20, 30); 
          } 
        } 
        catch (Exception ex) 
        { 
          Console.WriteLine(ex.Message); 
        } 

        Console.ReadLine(); 
      } 
    } 
+0

爲什麼不把錯誤處理放到循環中?如果發生異常,則繼續循環。 – mdcuesta

+0

感謝您的反饋。 –

回答

1

移動在try..catch:

foreach (TheMulticastDelegate multiCastDel in addition.GetInvocationList()) 
{ 
    try 
    { 
     multiCastDel(20, 30); 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.Message); 
    } 
} 

除此之外,您還願意與throw ;取代throw ex;因爲前者創建一個新的異常,這是不必要的。它應該看起來像:

private static void MultiCastDelMethod(int x, int y) 
{ 
    try 
    { 
     int zero = 0; 
     int z = (x/y)/zero; 
    } 
    catch (Exception ex) 
    { 
     throw ; 
    } 
} 
+0

沒有必要添加任何try catch。因爲你沒有處理任何事情,只是拋出異常。 – shankbond