我有一个多播委托,我正在调用两个方法。如果第一个方法中存在异常并处理它,如何继续第二个方法调用?我附上下面的代码。在下面的代码中,第一个方法抛出异常。但我想知道如何通过多播委托调用继续执行第二种方法。
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 :(得分: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 ;
}
}