Why AccessViolationException cannot be caught by .NET4.0

后端 未结 2 595
忘掉有多难
忘掉有多难 2020-12-01 06:34

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

C# code

class Program
{
    stat         


        
相关标签:
2条回答
  • 2020-12-01 07:01
        [HandleProcessCorruptedStateExceptions]
        public static unsafe int LenghtPoint(this IntPtr point)
        {
            //por optimizar
            byte* bytePoint = (byte*)point.ToPointer();
            byte auxByte;
            int length = 1;
            bool encontrado = false;
            while (!encontrado)
            {
    
                try
                {
    
                    auxByte = bytePoint[length];
                    length++;
                }
                catch (System.AccessViolationException)
                {
                    length--;
                    encontrado = true;
    
                }
            }
            return length;
        }
    
    0 讨论(0)
  • 2020-12-01 07:09

    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.

    0 讨论(0)
提交回复
热议问题