2

I have a method that calls an unmanaged library from a background thread. I put a try catch block around the unmanaged call but it is never caught. The just in time debugger catches it instead. What am I doing wrong?

    public bool TurnOn()
    {
        var connectionSucceeded = false;
        try
        {
            connectionSucceeded = turnOn(); //Unmanaged call
        }
        catch
        {
            connectionSucceeded = false; //Never reaches this block                
        }

        return connectionSucceeded;
    }
Robert
  • 6,086
  • 19
  • 59
  • 84

2 Answers2

1

Is the debugger setup to handle unmanaged exceptions when they are thrown?

Check the setting in Debug>Exceptions

Also, is the unmanaged exception definitely thrown on the thread directly being called - and not in some async operation on a different thread?

Stuart
  • 66,722
  • 7
  • 114
  • 165
  • Either way it should either show up in the catch block or the UnhandledException event. It does not do either. – Robert Mar 19 '11 at 19:29
  • If it's thrown on a new thread - one created by the native code - then I don't think it will show up in your handler. – Stuart Mar 19 '11 at 19:30
  • How would I catch something like that? – Robert Mar 19 '11 at 19:38
  • AFAIK, I'm not sure you can - if it's a native exception on a thread without any native try/catch handling, then I think that's game over. But first of all, is there any way you can check that this is actually the problem - e.g. what does the native stack trace show you? What is the native "turnon"? Is it something you have the pdb/dbg symbols or the source code for? – Stuart Mar 19 '11 at 19:56
  • I do not have any pdb/dbg symbols or any access to the source. – Robert Mar 19 '11 at 20:06
  • does the turnon method throw an exception if called from native code? - e.g. from a native C++ app? – Stuart Mar 19 '11 at 20:14
1

I fully agree with Stuart answer.. In this case you could try catch exception on application level:

AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventRaised;

Plz see also this answer: AppDomain.CurrentDomain.UnhandledException not firing without debugging

Community
  • 1
  • 1
mastak
  • 1,397
  • 1
  • 14
  • 28