What is a finalizer or destructor conceptually, and why are finalizers considered unreliable for resource cleanup?

Last updated 5 July 2026

  • A finalizer/destructor is a method the runtime may call just before an object is reclaimed, letting it release non-memory resources like file handles or sockets (e.g. C++ ~Class(), Python __del__). C++ stack destructors run predictably at scope exit (RAII).

  • In garbage-collected languages the GC decides if and when finalizers run. Timing isn't guaranteed, they may never run (e.g. at process exit), ordering is undefined, and they slow collection.

  • Use deterministic disposal instead: C# IDisposable with using, Java try-with-resources, Python with. Keep finalizers only as a leak safety net.

All Object-Oriented Programming interview questions