防止DLL中未处理的异常时应用程序崩溃

时间:2018-10-18 13:00:42

标签: c# dll

我正在研究C#WPF应用程序。我正在使用DLL(不是我开发的)。我正在这样使用(简化):

try
{
    Bitmap bmp = new Bitmap(filePath);

    // Use the DLL
    var worker = theDLL.loadImage(bmp);

    status state = worker.start();

    if (state = theDLL.sta.OK)
    {
        return "OK"
    }
    else
    {
        state = worker.tryOtherMethod();
    }
}
catch (Exception e)
{
    // Do something with e
}

有时(并非总是)我有一个未处理的异常。此异常未捕获,我的应用程序崩溃了:

  

无效的参数传递给认为无效的函数   参数致命。

我看到此异常来自C ++代码,但我无法捕获它(即使使用AppDomain.CurrentDomain.UnhandledExceptionDispatcher.UnhandledException也是如此)。

如何防止崩溃?

编辑:

我尝试单独使用catchcatch (Win32Exception e)来捕获异常,但都不能解决我的问题。

我仍然有此错误:

enter image description here

1 个答案:

答案 0 :(得分:0)

您只能编写catch(不写(Exception e)),这将允许您捕获本机异常。

try
{
    Bitmap bmp = new Bitmap(filePath);

    // Use the 
    var worker = theDLL.loadImage(bmp);

    status state = worker.start();

    if (state = theDLL.sta.OK)
    {
        return "OK"
    }
    else
    {
        state = worker.tryOtherMethod();
    }
}
catch (Exception e)
{
    // Exceptions derived from Exception
}
catch
{
    // Native exceptions
}
相关问题