来自外部 DLL 的未处理的 DivideByZero 异常 - C#

Unhandled DivideByZero exception from an external DLL - C#

我有一个 C# (.net 4.0) 程序,其主要是从外部 FTP 库调用方法 - 项目引用的 dll。逻辑在 try-catch 块中,catch 打印错误。异常处理程序有一个通用参数:catch(Exception ex)。 IDE VS.

有时 FTP 库会抛出以下被零除异常。问题是它 not 被 catch 块捕获,程序崩溃了。 捕获了源自我的包装器代码的异常。任何人都知道有什么区别以及如何捕获异常?

异常:

Description: The process was terminated due to an unhandled exception.
Exception Info: System.DivideByZeroException
Stack:
   at ComponentPro.IO.FileSystem+c_OU.c_F2B()
   at System.Threading.ExecutionContext.runTryCode(System.Object)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode, CleanupCode, System.Object)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart()

描述了一个类似的问题here and also here以供解释。正如评论之一所述,FTP 服务器应始终自行处理协议违规而不会崩溃。如果可以,您应该选择另一个 FTP。但是,如果您想继续使用该 DLL,您需要像 Blorgbeard 指出的那样在应用程序域级别处理异常。

这里是如何使用 AppDomain.UnhandledException 事件捕获异常的示例:

using System;
using System.Security.Permissions;

public class Test
{

   [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
   public static void Example()
   {
       AppDomain currentDomain = AppDomain.CurrentDomain;
       currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

       try
       {
          throw new Exception("1");
       }
       catch (Exception e)
      {
         Console.WriteLine("Catch clause caught : " + e.Message);
      }

      throw new Exception("2");

      // Output: 
      //   Catch clause caught : 1 
      //   MyHandler caught : 2
   }

  static void MyHandler(object sender, UnhandledExceptionEventArgs args)
  { 
     Exception e = (Exception)args.ExceptionObject;
     Console.WriteLine("MyHandler caught : " + e.Message);
  }

  public static void Main()
  {
     Example();
  }

}