Why is this an issue?
Finalizers (historically referred to as destructors) 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 destructor is called; the garbage collector decides when to call it, and the destructor
implicitly calls Finalize
on the object’s base class.
When you create a destructor, you should never throw an exception in it, as you are risking having your application terminated without a graceful
cleanup.
If a destructor throws an exception, and the runtime is not hosted by an application that overrides the default policy and the behavior of the
UnhandledExceptionEventHandler
, then the runtime terminates the process immediately without graceful cleanup (finally
blocks
and Finalizer
methods are not executed).
The rule raises an issue on throw
statements used in destructors.
Noncompliant code example
class MyClass
{
~MyClass()
{
throw new NotImplementedException(); // Noncompliant
}
}
Compliant solution
class MyClass
{
~MyClass()
{
}
}
Resources
Documentation