0

In the following code I want to read data by using Marshal. The function itself is working fine (as long as the length fits to the pointer of course). I wrote a unit test to check some possible outcomes of copyDataFromMemory and noticed that the AccessViolationException is thrown, but my test stops right there and doesn't execute my catch-block. Here's my code:

private static double[] copyDataFromMemory(PointerLengthPair pointerLengthPair)
{
     double[] dataChain = new double[pointerLengthPair.Length];
     try
     {
         Marshal.Copy(pointerLengthPair.Pointer, dataChain, 0, pointerLengthPair.Length);
     }
     catch (AccessViolationException)
     {        
         return null;
     }
     catch (Exception)
     {
         return null;
     }

     return dataChain;
}

public class PointerLengthPair
{
    public IntPtr Pointer { get; private set; }
    public int Length { get; private set;}

    public PointerLengthPair(IntPtr pointer, int length)
    {
        Pointer = pointer;
        Length = length;
    }
}

Now my question is: Is this some sort of problem with Visual Studio 2012? Are there settings I have to choose or is it just not possible to catch a AccessViolationException? Or do I miss something obvious?

(note: please ignore that I'm currently using null as return value. I will replace this with an object of a new class as soon as possible)

Mickey
  • 943
  • 1
  • 19
  • 41
  • You should try reading the documentation for AccessViolationException: "Starting with the .NET Framework 4, AccessViolationException exceptions thrown by the common language runtime are not handled by the catch statement in a structured exception handler if the exception occurs outside of the memory reserved by the common language runtime. [...]" – Jon Jul 07 '14 at 11:41
  • Thank you. Seems like I've overlooked that part. – Mickey Jul 07 '14 at 11:45

0 Answers0