多播委托中的异常处理

本文关键字:异常处理 多播 | 更新日期: 2023-09-27 17:49:39

我有一个多播委托,我通过它调用两个方法。如果在第一个方法中存在异常并已处理,如何继续第二个方法调用?我附上下面的代码。在下面的代码中,第一个方法抛出异常。但我想知道如何继续执行第二个方法通过多播委托调用。

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

多播委托中的异常处理

将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 ;
    }
}