#672 – An Exception Thrown From a Finalizer Will Be Treated as an Unhandled Exception

If an exception originates in a finalizer in C# and is not handled within the body of the finalizer, the exception will be treated by the application as an unhandled exception.  If you have no mechanism for dealing with unhandled exceptions, this will lead to a crash.

In the example below, the exception originating in the Dog finalizer is not caught within the Main method.

        static void Main()
        {
            try
            {
                Dog d = new Dog();
                d = null;

                GC.Collect();
                GC.WaitForPendingFinalizers();

                Console.WriteLine("I made it to the end of the program");
                Console.ReadLine();
            }
            catch (Exception xx)
            {
                Console.WriteLine(string.Format("Hey, I caught an exception! {0}", xx.ToString()));
            }
    public class Dog
    {
        public Dog()
        {
            Console.WriteLine("Dog constructor");
        }

        ~Dog()
        {
            Console.WriteLine("Dog finalizer running");
            throw new Exception("** Exception from Dog finalizer **");
        }
    }

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: