Ram
Ram

Reputation: 11644

Do we really need to catch exception for P/Invoke methods?

I am using P/Invoke methods in my .NET application. As the functions are C++ functions; each one has return type like int, intptr or any struct. The return type is enough to tell me if the function was successful or not. Do I still need to catch generic or COM exception in this case?

Upvotes: 2

Views: 322

Answers (3)

Windows programmer
Windows programmer

Reputation: 8065

C++ functions can generate exceptions.

Windows APIs can generate exceptions whether they're called directly from P/Invoke or from C++ functions.

Is it OK for your users to see exception messages (error messages) from Windows or do you want your program to display your message to them?

Upvotes: 1

Rhapsody
Rhapsody

Reputation: 6077

In my opinion you should always use try/catch when invoking an external component. You never know what can be returned. Prepare for the unexpected :)

Upvotes: 2

Alex F
Alex F

Reputation: 43321

PInvoke call still may fail if Dll is not found, or doesn't contain required function.

Upvotes: 2

Related Questions