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