Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

c# - Why AccessViolationException cannot be caught by .NET4.0

It is really interesting that the following C# code will crash on .NET4.0 but work fine on .NET2.0.

C# code

class Program
{
    static void Main(string[] args)
    {
        try
        {
            ExceptionTest();
            Console.WriteLine("Done!");
        }
        catch (Exception e)
        {
            Console.WriteLine("Error !!!");
            Console.WriteLine(e.Message);
        }
    }

    [DllImport("badapp")]
    private static extern int ExceptionTest();
}

C++ code

extern "C" __declspec(dllexport) int ExceptionTest()
{
    IUnknown* pUnk = NULL;
    pUnk->AddRef();
    return 0;
}

If compiling the above C# code against .NET2.0, everything works fine. Only compiling it against .NET4.0 will make it crash at runtime.

I'm suspecting that system exception catch mechanism has been changed since .NET4.0. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, it changed in .NET 4. You cannot catch exceptions that indicate a corrupted state. This is because there's pretty much no guarantee that you can do anything at all when a corrupted state exception is thrown. There is practically no reason to want a process with corrupted state to continue executing.

For compatibility with older code, you can change this behaviour by adding the legacyCorruptedStateExceptionsPolicy element to app.config.

You can also do it on a case-by-case basis by marking methods where you want to catch these exceptions with the HandleProcessCorruptedStateExceptions attribute.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...