1

2 つのメソッドを呼び出しているマルチキャスト デリゲートがあります。最初のメソッドとその処理で例外が発生した場合、2 番目のメソッドの呼び出しを続行するにはどうすればよいですか? 以下にコードを添付します。以下のコードでは、最初のメソッドが例外をスローします。しかし、マルチキャスト デリゲート呼び出しを介して 2 番目の方法を実行し続ける方法を知りたいです。

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();
            }
    }
4

1 に答える 1

1

try..catch をループ内に移動します。

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

また、前者は不要な新しい例外を作成するthrow ex;ため、に置き換えます。throw ;次のようになります。

private static void MultiCastDelMethod(int x, int y)
{
    try
    {
        int zero = 0;
        int z = (x / y) / zero;
    }
    catch (Exception ex)
    {
        throw ;
    }
}
于 2012-12-28T06:04:49.900 に答える