Search code examples
c#exceptiondllunhandled-exception

Not able to catch exception on DLL function call c#


i'm developing an app that use external DLL to program drivers ( i have not DLL source code ). In one of that DLL there is a function ( to read driver information) that, in a specific situation, throw an exception (NFCExceptionReadingFailure) that make my app crash. Now i will show you the code to explain better:

ReadbackFileAvailableEventArgs Driver_INFO;

public void HandleReadbackCompletedEvent(ReadbackFileAvailableEventArgs DINFO)
{
    Driver_INFO = DINFO;
}

public Tuple<string, string, string, string, string> getDriverINFO()
{
    // Unsubscribe first
    ReadbackCompletedEvent -= HandleReadbackCompletedEvent;
    // then Subscribe 
    ReadbackCompletedEvent += HandleReadbackCompletedEvent;

    //With this line of code reading process is started on the DLL ( ReadFromDevice is a method of the dll)
    ProgrammingAPI.ApplicationConstants.ReturnCode ret = ReadFromDevice();

    //ret is Success if the process is started on the DLL
    if (ret == ApplicationConstants.ReturnCode.Success)
    {
        Console.Write("\nREADING...");
        // wait for programming or readback completion
        while (ProgrammingAPI.ProgrammingAPI.IsWorking())
        {
            Console.Write(".");
            Thread.Sleep(500);
        }

        Console.Write("\READING OK");
        .......
    }
}

I found that in a situation the reading process start correctly ( ret = Success ) but during the process the DLL throw an exception that make my app crash.

Placing the try catch on ReadFromDevice calling is useless ( this method is always executed correctly ). If i put the while inside a try catch the DLL exception still make my app crash.

There is a way to manage this situation and prevent app crash?


Solution

  • I have published my app as a windows services and the unamanged exception doesn't make my app crash anymore. Now is seen as simple app error and i can use the software.