我在.net应用程序中使用COM对象(MODI)。我调用的方法抛出System.AccessViolationException
,它被Visual Studio拦截。奇怪的是,我已经将我的调用包装在一个try catch中,它有AccessViolationException
、COMException
和其他所有东西的处理程序,但当Visual Studio(2010)拦截AccessViolationException
时,调试器在方法调用(doc.OCR)上中断,如果我跨步执行,它将继续到下一行,而不是进入catch块。此外,如果我在visual studio之外运行这个程序,我的应用程序会崩溃。如何处理COM对象中抛出的异常?
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 = "";
}
catch
{
sText = "";
}
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();
}