title: How to handle AccessViolationException
body: <p>I am using a COM object (MODI) from within my .net application.  The method I am calling throws a <code>System.AccessViolationException</code>, which is intercepted by Visual Studio.  The odd thing is that I have wrapped my call in a try catch, which has handlers for <code>AccessViolationException</code>, <code>COMException</code> and everything else, but when Visual Studio (2010) intercepts the <code>AccessViolationException</code>, the debugger breaks on the method call (doc.OCR), and if I step through, it continues to the next line instead of entering the catch block. Additionally,  if I run this outside of the visual studio my application crashes. How can I handle this exception that is thrown within the COM object?</p>
  <pre><code>MODI.Document doc = new MODI.Document();
  try
  {
      doc.Create(sFileName);
      try
      {
          doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, false, false);
          sText = doc.Images[0].Layout.Text;
      }
      catch (System.AccessViolationException ex)
      {
          //MODI seems to get access violations for some reason, but is still able to return the OCR text.
          sText = doc.Images[0].Layout.Text;
      }
      catch (System.Runtime.InteropServices.COMException ex)
      {
          //if no text exists, the engine throws an exception.
          sText = &quot;&quot;;
      }
      catch
      {
          sText = &quot;&quot;;
      }
  
      if (sText != null)
      {
          sText = sText.Trim();
      }
  }
  finally
  {
      doc.Close(false);
  
      //Cleanup routine, this is how we are able to delete files used by MODI.
      System.Runtime.InteropServices.Marshal.FinalReleaseComObject(doc);
      doc = null;
      GC.WaitForPendingFinalizers();
      GC.Collect();
      GC.WaitForPendingFinalizers();
  
  }
  </code></pre>