【问题标题】:Unhandled DivideByZero exception from an external DLL - C#来自外部 DLL 的未处理的 DivideByZero 异常 - C#
【发布时间】:2015-05-19 05:22:18
【问题描述】:

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

有时 FTP 库会引发以下除以零异常。问题是它没有被 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()

【问题讨论】:

  • 看起来异常发生在不同的线程中。尝试处理AppDomain.UnhandledException

标签: c# .net exception dll exception-handling


【解决方案1】:

herehere 描述了一个类似的问题以供解释。正如其中一个 cmets 所述,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();
  }

}

【讨论】:

    猜你喜欢
    • 2017-04-22
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 2011-11-21
    • 2020-05-08
    • 2011-02-20
    • 2020-04-07
    • 1970-01-01
    相关资源
    最近更新 更多