The Finalize methods are used to perform any necessary final clean-up when the garbage collector is collecting a class instance. The programmer has no control over when the Finalize method is called; the garbage collector decides when to call it.
When creating a Finalize method, it should never throw an exception, as there is a high risk of having the application terminated leaving unmanaged resources without a graceful cleanup.
The rule raises an issue on throw statements used in a Finalize method.
Class Sample
Protected Overrides Sub Finalize()
Throw New NotImplementedException() ' Noncompliant: Finalize method throws an exception
End Sub
End Class
Class Sample
Protected Overrides Sub Finalize()
' Noncompliant: Finalize method does not throw an exception
End Sub
End Class
In general object finalization can be a complex and error-prone operation and should not be implemented except within the dispose pattern.
When cleaning up unmanaged resources, it is
recommended to implement the dispose pattern or, to cover uncalled Dispose method by the consumer, implement SafeHandle.
SafeHandle
Class IDisposable.Dispose Method