
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Handling Exceptions Individually for Each Delegate in a Multicast Delegate
|
495
The following class contains each of the methods that will be called by the
MyDelegate multicast delegate instances:
public class TestInvoke
{
public static int Method1( )
{
Console.WriteLine("Invoked Method1");
return (1);
}
public static int Method2( )
{
Console.WriteLine("Invoked Method2");
return (2);
}
public static int Method3( )
{
// Simulate an exception being thrown.
throw (new Exception("Method3"));
Console.WriteLine("Invoked Method3");
return (3);
}
}
Discussion
If an exception occurs in a delegate that is invoked from within a multicast delegate
and that exception is unhandled, any remaining delegates are not invoked. This is
the expected behavior of a multicast delegate. However, in some circumstances,
you’d like to be able to handle exceptions thrown from individual delegates and then
determine at that point whether to continue invoking the remaining delegates.
In the
TestIndividualInvokesExceptions method of this recipe, if an exception
SecurityException is caught, it is logged to the event log and the exception is
rethrown. However, if another type of
Exception object is thrown, you just display or
log it and continue invoking delegates. This strategy allows for as fine-grained han-
dling of ...