尝试在不安全的代码中捕获异常

Den*_*nis 3 c# unsafe image-processing try-catch

我正在编写一些图像处理代码并使用C#进行低级像素操作.每隔一段时间就会发生一次accessViolationException.

有几种解决这个典型问题的方法,有些认为代码应该是健壮编写的,以便没有访问冲突异常,并且据我尝试,应用程序正常但是我想添加一个try catch,以便iff的东西是要发生这种情况,应用程序不会以太丑陋的方式失败.

到目前为止,我已经提供了一些示例代码来测试它

unsafe
{
    byte* imageIn = (byte*)img.ImageData.ToPointer();
    int inWidthStep = img.WidthStep;
    int height = img.Height;
    int width = img.Width;
    imageIn[height * inWidthStep + width * 1000] = 100; // make it go wrong
}
Run Code Online (Sandbox Code Playgroud)

当我试着抓住这个陈述时,我仍然得到一个例外.有没有办法捕获不安全块中生成的异常?

编辑:如下所述,除非通过将此属性添加到函数并添加"using System.Runtime.ExceptionServices"来显式启用它们,否则不再处理此类型的异常.

[HandleProcessCorruptedStateExceptions]
    public void makeItCrash(IplImage img)
    {
        try
        {
            unsafe
            {
                byte* imageIn = (byte*)img.ImageData.ToPointer();
                int inWidthStep = img.WidthStep;
                int height = img.Height;
                int width = img.Width;
                imageIn[height * inWidthStep + width * 1000] = 100; // to make it crash
            }
        }
        catch(AccessViolationException e)
        {
            // log the problem and get out
        }
    }
Run Code Online (Sandbox Code Playgroud)

Rob*_*ani 6

检查尺寸并返回ArgumentOutOfRangeException参数是否使您在图像外部书写.

An AccessViolationException是损坏的状态异常(CSE),而不是结构化异常处理(SEH)异常.从.NET 4开始,catch(Exception e)除非您使用属性指定它,否则不会捕获CSE.这是因为您应该首先编写避免CSE的代码.你可以在这里阅读更多相关信息:http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035