#672 – An Exception Thrown From a Finalizer Will Be Treated as an Unhandled Exception
September 17, 2012 Leave a comment
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 **"); } }