In this example I am creating a simple delegate which returns void and takes no parameter.
Like:
delegate void Opearation();
I have Also created three methods Add(),Sub(),Mul() with no input paramter and void as return type.
To handle exception in multicast delegate we need to use GetInvocationList() method.
See the Complete Code:
namespace EventDelegateTest{delegate void Operation();
class ExceptionInMulticaseDelegate
{
static Operation operation;
public static void Main()
{
operation += Add;
operation += Sub;
operation += Mul;
//This sttement will break application execution,becasue Sub methods throws an exception.
//operation();
foreach (Operation op in operation.GetInvocationList())
{
try{
op();
}
catch (Exception ex) { }
}
Console.ReadLine();// just to see result on console.(i.e. to stop main to finish).
}
public static void Add()
{
Console.WriteLine("Add");
}
public static void Sub()
{
throw new Exception();
}
public static void Mul()
{
Console.WriteLine("Mul");
}
}
}
In the above example delegate Operation will call Add(),Sub() and Mul() methods but as we can see Sub() method will throw exception which will terminate program abnormally, if we call delegate in usual way (as I have commented code //Operation(); before foreach loop in code).
So, the right way to handle exceptions in multicast delegate is, call delegate's GetInvocationList() method and loop through it and handle exception inside loop.
In this case, your program will not terminate abnormally , it will continue execution for other subscribed methods.
Otuput of above program :
Add
Mul