Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 619
Tarun Avatar asked Dec 29 '22 04:12

Tarun


2 Answers

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.

like image 118
Brian Rasmussen Avatar answered Jan 14 '23 12:01

Brian Rasmussen


its HandleProcessCorruptedStateExceptions not HandleDProcessCorruptedStateExceptions

like image 28
Yaz Avatar answered Jan 14 '23 12:01

Yaz