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

时间:2012-11-07 01:09:14

标签: c# image-processing try-catch unsafe

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

这个典型问题有几种方法,有些认为代码应该是健壮编写的,以便没有访问冲突异常,而且据我尝试,应用程序运行正常但是我想添加一个try catch以便如果发生了某些事情,应用程序就不会因为太丑陋而失败。

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

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
}

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

编辑:如下所述,除非通过将此属性添加到函数并添加“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
        }
    }

1 个答案:

答案 0 :(得分:6)

如果参数让您在图像外写字,请检查尺寸并返回ArgumentOutOfRangeException

AccessViolationException是损坏的状态异常(CSE),而不是结构化异常处理(SEH)异常。从.NET 4开始,除非您使用属性指定,否则catch(Exception e)将无法捕获CSE。这是因为您应该首先编写避免CSE的代码。您可以在此处详细了解:http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035

相关问题