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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: