How do I catch an Interop exception?

十年热恋 提交于 2019-12-12 02:22:29

问题


I am trying to catch an Interop Exception in my C# code

IEngine engine = null;

try
{
    engine = engineLoader.GetEngineObject(AbbyySdkSerialNumber);
}
catch(System.Runtime.InteropServices.COMException ex)
{
    int i = 0;
}

but it does not want to jump into catch block. Any ideas? Thank you in advance!


回答1:


The CLR automatically maps the HRESULT from COM interop to more specific managed exceptions, not to COMException. For example, E_ACCESSDENIED becomes UnauthorizedAccessException, E_OUTOFMEMORY becomes OutOfMemoryException, and so on.

If the HRESULT is a custom result or if it is unknown to the CLR, then the runtime does pass a generic COMException to the client. The ErrorCode property of the COMException contains the HRESULT value.

For a complete discussion of COM interop, see Advanced COM Interoperability.

Note that if you're running this under the VS debugger then by default execution will stop on the line that caused the exception. It won't jump to the catch block unless you then step to the next line.




回答2:


If it is definitely throwing an exception then I'll bet it's not actually throwing the type of exception you expect, i.e. System.Runtime.InteropServices.COMException. I'd suggest adding a catch (Exception ex) clause to the try in order to firstly check my sanity, then secondly examine the exception that is being thrown.




回答3:


I have the same exception. It says me that the project id is wrong - that should be the serial number you'll be inserting inside to object during initialization.

Advice: Check this first, if you're running in trial then if it isn't expired.

My exception occurred when I run SDK via win service. Service starts as local service and did not work because of unavailability to create engine object by GetEngineObject. I also tried to create object GetEngineObject via different user name (process) but it did not help. The thing is why I consider the user name difference that I create console app in my visual studio, there I put my code to it and run in debug mode in VS it works! (vs runs in my user name)

I do not know what is wrong ...




回答4:


For my case, I needed to catch the exact type of the generated exception. It was being generated an exception of type System.IO.IOException in managed part of code, and in my unmanaged code I needed to do a catch(IOException ^), what solved the problem. Or else the exception was never caught even using a catch(Exception ^).



来源:https://stackoverflow.com/questions/15552036/how-do-i-catch-an-interop-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!