Avoid exceptions in finalizers

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: csharp-best-practices/finalizer-no-exception

Language: C#

Severity: Warning

Category: Best Practices

Description

Do not throw exceptions in finalizer blocks, as it can terminate the whole process if handled incorrectly.

From the official documentation: “If Finalize or an override of Finalize throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process and no active try/finally blocks or finalizers are executed”.

Learn More

Non-Compliant Code Examples

using System.Xml;

class MyClass {
    ~MyClass()
    {
        if (foo) {
            throw new MyException();
        }
        
    }
}
using System.Xml;

class MyClass {
    ~MyClass()
    {
        throw new MyException();
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis