#376 – What Happens When an Exception Occurs During Delegate Invocation

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

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #376 – What Happens When an Exception Occurs During Delegate Invocation

  1. Pradip says:

    Nice! Really help full for me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: