c# finalizer throwing exception?

2020-03-01 08:45发布

问题:

Quote from MSDN:

If Finalize or an override of Finalize throws an exception, the runtime ignores the exception, terminates that Finalize method, and continues the finalization process.

Yet if I have:

~Person()
{
throw new Exception("meh");
}

then it results in a runtime exception?

p.s. I know that this should never happen, however I'm just curious around this behaviour. One of our clients had an empty try catch around all of their finalizers.. it didn't even log when things went wrong or reserect the object :/

回答1:

Linking the source of your quote is important. I have to assume it talks about an old version of .NET, perhaps version 1.x. It tried to be "tolerant" of unhandled exceptions, swallowing them without a squeak. That did not work out well, chunks of code silently failing is extraordinarily hard to debug.

The .NET 2.0 version put an end to that, the default CLR host terminates the app for any unhandled exception. An exception in a finalizer is fatal.