gpt4 book ai didi

c# - try catch 不安全代码中的异常

转载 作者:行者123 更新时间:2023-11-30 14:34:53 24 4
gpt4 key购买 nike

我正在编写一些图像处理代码并使用 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
}

当我对这个语句进行 try catch 时,我仍然得到一个异常。有没有办法捕获不安全 block 中生成的异常?

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

最佳答案

检查尺寸并返回一个 ArgumentOutOfRangeException 如果参数让您在图像之外书写。

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

关于c# - try catch 不安全代码中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13261875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com