c# finalizer throwing exception?
Asked Answered
R

2

17

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 :/

Recti answered 22/4, 2010 at 15:9 Comment(6)
You should never use finalizers anyway. Never as in, unless you know exactly why you have to use that.Shawnee
"then it results in a runtime exception?" Are you saying you've tried this and it does result in an exception? Or are you asking us to test this?Keg
it DOES result in a runtime exception. Dykam, thanks for telling me I should never use finalizers... lol!Recti
Finalizers are for releasing unmanaged resources. Managed resources are in an indeterminant state while the Finalizer is running. If you're throwing an exception in a finalizer, then you should change your design pattern to prevent the exception from occurring (i.e. check the file exists before accessing, etc)Garton
Read my post! "I know that this should never happen" This isn't a specific question, just a generalization since this was mentioned in the O'Reilly .NET 4.0 book AND on some old MSDN documentation.Recti
Finalizers should clean up resources that the programmer forgot to do himself. If your class has a close() method that the client code never calls, then your destructor/finalizer must do the cleanup.Heffner
L
27

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.

Lanate answered 22/4, 2010 at 15:21 Comment(2)
thanks Hans. I originally found the quote from the new O'Reilly .NET 4.0 book, however the quote was from .NET 1.1. Maybe they should update the book ;) ThanksRecti
MSDN links: 4.0 msdn.microsoft.com/en-us/library/… 1.1 msdn.microsoft.com/en-us/library/…Chaldean
G
0

I'm curious as to what happens in xamarin since i've seen this happen in production and the android app did not crash, it is possible that a lock occurred on the finalizer thread and the app ran sub-par until restart.

Gowen answered 6/5, 2021 at 4:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.