如何处理在外部dll上引发的异常

本文关键字:dll 异常 外部 何处理 处理 | 更新日期: 2023-09-27 18:00:23

我开发了一个使用外部dll作为FTPServer的项目,我在我的项目上创建了FTP服务器,如下所示:

private ClsFTPServer _ClsFTPServer;
_ClsFTPServer = new ClsFTPServer(FTPUserName, FTPPassword, FTPPath);

上面的代码创建了FTP服务器类的一个实例,该类在其构造函数上启动FTPserver,当客户端正确发送请求时,它作为一个模块独立运行良好,但当不正确的请求到达FTP服务器时,它会引发异常,导致我的应用程序崩溃。

如何处理外部dll引发的异常以防止应用程序崩溃?

如何处理在外部dll上引发的异常

我最近回答了一个类似的(ish)问题,这个问题可能很有用-捕获完全意外的错误

编辑。我不得不同意汉斯在上面的评论——也许是一个寻找另一个FTP服务器的想法。

为了完整起见,以下是-http://msdn.microsoft.com/en-GB/library/system.windows.forms.application.threadexception.aspx

Application.ThreadException += new ThreadExceptionEventHandler  (ErrorHandlerForm.Form1_UIThreadException);
// Set the unhandled exception mode to force all Windows Forms errors to go through 
// our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event. 
AppDomain.CurrentDomain.UnhandledException +=
    new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

如果使用外部非托管''不安全代码。NET(高于.NET 4)默认情况下无法处理dll代码内部发生的内存访问冲突异常。为了抓住这些例外,有三件事要做。我做到了,而且对我有效:

  1. 将这些属性添加到发生异常的方法中:
    (调用非托管代码的方法的方法。)

    [HandleProcessCorruptedStateExceptions]
    [SecurityCritical]
    
  2. 将此标签添加到应用程序。运行时标签下方的配置文件:

    <runtime>
    <legacyCorruptedStateExceptionsPolicy enabled="true"/>
    <!-- other tags -->
    </runtime>
    
  3. 使用System捕获此类异常。AccessViolationException异常类型:

      try{
            //Method call that cause Memory Access violation Exeption
         }
    catch (System.AccessViolationException exception)
         {
            //Handle the exception here
          }
    

我所说的正是解决这类异常的良方。有关此异常的自我以及此方法如何工作的更多信息,请参阅系统。AccessViolationException

您可能已经尝试过了,但以防万一,您是否尝试过将其封装在try catch中?

try
{
    _ClsFTPServer = new ClsFTPServer(FTPUserName, FTPPassword, FTPPath);
    ...
}
catch(Exception e)
{
    ...
}

通过尝试。。。catch块围绕对对象及其方法的每次调用。

类似于:

try
{
    // use the DLL in some way
}
catch (Exception e) 
{
    // Handle the exception, maybe display a warning, log an event, etc.)
}

另请注意,在Visual Studio下运行时,如果转到"调试"菜单并选择"异常…",则如果在调试器下启动程序,调试器将允许中断所有异常,而不仅仅是未处理的异常。只需单击"公共语言运行时异常"旁边的"抛出"复选框。

相关文章: