我有一个 C# (.net 4.0) 程序,其主要是从外部 FTP 库调用方法 - 项目引用的 dll。逻辑在 try-catch block 中,catch 打印错误。异常处理程序有一个通用参数:catch(Exception ex)
。 IDE是VS。
有时 FTP 库会抛出以下被零除异常。问题是它没有被catch block 捕获,程序崩溃了。 捕获了源 self 的包装器代码的异常。任何人都知道有什么区别以及如何捕获异常?
异常:
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还有here解释。正如评论之一所述,FTP 服务器应始终自行处理协议(protocol)违规而不会崩溃。如果可以,您应该选择另一个 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();
}
}
关于c# - 来自外部 DLL 的未处理的 DivideByZero 异常 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29087947/