代码之家  ›  专栏  ›  技术社区  ›  A.Pissicat

防止应用程序在dll中出现未处理的异常时崩溃[duplicate]

  •  0
  • A.Pissicat  · 技术社区  · 6 年前

    我正在开发一个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
    }
    

    有时(并非总是)我有一个未处理的异常。此异常不是catch和我的应用程序崩溃:

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

    我看到这个异常来自C++代码,但我无法捕捉到它(即使是 AppDomain.CurrentDomain.UnhandledException Dispatcher.UnhandledException ).

    我怎样才能防止撞车?

    编辑:

    我试图抓住这个例外 catch 孤零零 catch (Win32Exception e) 但这两个都没有解决我的问题。

    我仍然有这个错误:

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   SᴇM    6 年前

    你只能写 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
    }