#376 – What Happens When an Exception Occurs During Delegate Invocation
July 27, 2011 1 Comment
When you invoke a delegate, it will call each of the methods in its invocation list, one at a time. If an exception is thrown from within one of those methods, the delegate will stop invoking methods in its invocation list and throw an exception up to the caller that initiated the invocation. Methods on the invocation list that haven’t already been called will not get called.
In the example below, the delegate’s invocation list has two methods–Method1 and Method2. Method1 raises an exception and Method2 is never called.
private delegate void StringHandlerDelegate(string s); static void Main() { try { // Add two methods to delegate instance StringHandlerDelegate del = Method1; del += Method2; // Invoke del("Yooper"); } catch (Exception xx) { Console.WriteLine("Exception: {0}", xx.Message); } } static void Method1(string text) { Console.WriteLine("Method1, {0}", text); throw new Exception("Problem in Method1"); } static void Method2(string name) { Console.WriteLine("Method2, {0}", name); }
Nice! Really help full for me.