Why is this an issue?
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.
How to fix it
Code examples
Noncompliant code example
Class Sample
Protected Overrides Sub Finalize()
Throw New NotImplementedException() ' Noncompliant: Finalize method throws an exception
End Sub
End Class
Compliant solution
Class Sample
Protected Overrides Sub Finalize()
' Noncompliant: Finalize method does not throw an exception
End Sub
End Class
Going the extra mile
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
.
Resources
Documentation