Tarun
Tarun

Reputation: 393

Handling AccessViolation exception in try catch c#

How to catch the AccessViolation exception in try-catch block:

here is the code below:

public static BP GetBloodPressure(string vendorid, string productid)
{
    BP Result = new BP();
    try
    {
        GETBPData BPreadings = new GETBPData();
        UInt16 VendorId = Convert.ToUInt16(vendorid, 16);
        UInt16 ProductId = Convert.ToUInt16(productid, 16);

        if (HealthMonitorData.HidDataTap_GetBloodPressure(VendorId, ProductId, ref BPreadings)) // error here
        {

            if (BPreadings.ucSystolic == 0 && BPreadings.ucDiastolic == 0 && BPreadings.DeviceId1 == 0 && BPreadings.DeviceId2 == 0 && BPreadings.ucPulse == 0)
            {
                Result = null;

            }
            else
            {
                Result.UcSystolic = BPreadings.ucSystolic;
                Result.UcDiastolic = BPreadings.ucDiastolic;
                Result.UcPulse = BPreadings.ucPulse;
                Result.DeviceId1 = BPreadings.DeviceId1;
                Result.DeviceId2 = BPreadings.DeviceId2;
            }
        }
    }
    catch (Exception ex)
    {

    }
        return Result;
}

I am importing one dll to read the blood pressure values from the device. I have try to catch the exception but the control does not go beyond the "if" statement where the access violation exception is coming.

Kindly Suggest?

Thanks

Upvotes: 4

Views: 1685

Answers (2)

Yaz
Yaz

Reputation: 21

its HandleProcessCorruptedStateExceptions not HandleDProcessCorruptedStateExceptions

Upvotes: 2

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

Handling of AccessViolationExceptions and other corrupted state exceptions has been changed in .NET 4. Generally you should not catch these exceptions, so the runtime has been changed to reflect this. If you really need to catch these, you must annotate the code with the HandledProcessCorruptedStateExceptions attribute.

Please keep in mind, that the behavior was changed with good reason. Most applications will not be able to handle these exceptions in any meaningful way and thus should not catch them.

Upvotes: 8

Related Questions