Wednesday, March 22, 2017

Catch Exception - Attempted to read or write protected memory in ESRI ArcObjects .Net 4.0 Framework

First - Don't write the code to throw "Attempted to read or write protected memory" ..it is bad.

Second - If you are working on legacy codes and COM objects that throws "Attempted to read or write protected memory" while writing ArcMap add-ins, catch exceptions to prevent application crash, in my case ArcMap.


Step #1 - Add following snippet to config file - app.config for Arc-addin

<configuration>
   <runtime>
      <legacyCorruptedStateExceptionsPolicy enabled="true" />
   </runtime>
</configuration>
Step #2

Add -

[HandleProcessCorruptedStateExceptions] 
[SecurityCritical]
on the top of function you are tying catch the exception

[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
public IFeatureLayer GetOrCreateFeatureLayer(string path, esriGeometryType type, ISpatialReference sr)
{
//body
}



Details-
// This program runs as part of an automated test system so you need 
// to prevent the normal Unhandled Exception behavior (Watson dialog). 
// Instead, print out any exceptions and exit with an error code. 
[HandleProcessCorruptedStateExceptions] 
[SecurityCritical]
public static int Main() 
{ 
   try
     {
       // Catch any exceptions leaking out of the program CallMainProgramLoop(); 
     }
   catch (Exception e) 
       // We could be catching anything here 
     {
         // The exception we caught could have been a program error
        // or something much more serious. Regardless, we know that
        // something is not right. We'll just output the exception 
       // and exit with an error. We won't try to do any work when
       // the program or process is in an unknown state!

        System.Console.WriteLine(e.Message); 
        return 1; 
     } 

  return 0; 

}

Ref-
https://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035
http://stackoverflow.com/questions/3469368/how-to-handle-accessviolationexception



.NET , ArcGIS , ArcMap , arcobject , C#

0 comments :

Post a Comment

 

© 2011 GIS and Remote Sensing Tools, Tips and more .. ToS | Privacy Policy | Sitemap

About Me