Unhandled DivideByZero exception from an external

2019-05-24 13:15发布

I have a C# (.net 4.0) program, whose main is calling methods from an external FTP library - a dll the project references. The logic is in a try-catch block, and the catch prints the error. The exception handler has a generic parameter: catch(Exception ex). The IDE is VS.

Sometimes the FTP library throws the following division by zero exception. The problem is it is not caught in the catch block, and the program crashes. Exceptions originated in my wrapper code are caught. Anyone has any idea what the difference is and how the exception can be caught?

The exception:

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()

1条回答
啃猪蹄的小仙女
2楼-- · 2019-05-24 13:54

There is a similar problem described here and also here for explanation. As said in one of the comments an FTP server should always handle protocol violations itself without crashing. You should pick another FTP if you can. However, if you want to keep using that DLL you need to handle the exception at App Domain level as Blorgbeard pointed out.

Here an example of how catch the exception using the AppDomain.UnhandledException event:

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();
  }

}
查看更多
登录 后发表回答