Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try catch exceptions in unsafe code

I am writing some image processing code and use C# to do low level pixel manipulation. Every once in a while, an accessViolationException happens.

There are several approaches to this typical problem, some think code should be written robustly so to not have access violation exceptions, and as far as I try, the application is going fine however I would like to add a try catch so that iff something were to happen, the application would not fail in too ugly of a way.

So far, I have put in some example code to test it out

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
}

When I put a try catch around this statement, I still get an exception. Is there a way to catch exceptions generated in an unsafe block?

Edit: as stated down below, this type of exception is no longer handled unless the checking of them is explicitly enabled by adding this attribute to the function and adding the "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
        }
    }
like image 459
Denis Avatar asked Dec 30 '25 00:12

Denis


1 Answers

Check the sizes and return an ArgumentOutOfRangeException if the parameters make you write outside of the image.

An AccessViolationException is a Corrupted State Exception (CSE), not a Structured Exception Handling (SEH) exception. Starting with .NET 4, catch(Exception e) won't catch CSE's unless you specify it with an attribute. This is because you should write code that avoids CSE's in the first place. You can read more about it here: http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035

like image 148
Robert Rouhani Avatar answered Jan 01 '26 14:01

Robert Rouhani