在Windows窗体应用程序中捕获应用程序exception

无论如何都要捕获代码中任何地方引发的探测? 我想捕获exception并以类似的方式处理它们,而不是为每个function编写try catch块。

在Windows窗体应用程序中,当在应用程序中的任何位置(在主线程上或在异步调用期间)抛出exception时,您可以通过在Application上注册ThreadException事件来捕获它。 通过这种方式,您可以以相同的方式处理所有exception。

Application.ThreadException += new ThreadExceptionEventHandler(MyCommonExceptionHandlingMethod); private static void MyCommonExceptionHandlingMethod(object sender, ThreadExceptionEventArgs t) { //Exception handling... } 

我认为这是一个接近,因为你可以在win form应用程序中找到你想要的东西。

http://msdn.microsoft.com/en-us/library/ms157905.aspx

 // Add the event handler for handling UI thread exceptions to the event. 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); 

如果不执行所有这些步骤,您可能会遇到一些未处理的exception风险。

显而易见的答案是将exception处理程序放在执行链的顶部。

 [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { Application.Run(new YourTopLevelForm()); } catch { //Some last resort handler unware of the context of the actual exception } } 

这将捕获主GUI线程上发生的任何exception。 如果您还想全局捕获在所有线程上发生的exception,您可以订阅AppDomain.UnhandledException事件并在那里处理。

 Application.ThreadException += new ThreadExceptionEventHandler(MyCommonExceptionHandlingMethod) private static void MyCommonExceptionHandlingMethod( object sender, ThreadExceptionEventArgs t) { //Exception handling... } 

代码复制自Charith J的答案

现在提出建议……

这些选项应该仅作为最后的手段使用,例如,如果您想要禁止从呈现给用户的意外未捕获的exception。 当你知道关于exception情况的某些事情时,你应该尽可能早地抓住。 更好的是,您可以对此问题采取一些措施。

结构化exception处理可能看起来像是一个不必要的开销,你可以解决所有问题,但它存在,因为事实并非如此。 更重要的是,这项工作应该在编写代码时完成,而开发人员的逻辑则是新鲜的。 不要懒惰,留下这项工作以供日后使用,或让一些更专业的开发人员接受。

如果您已经知道并且这样做,请道歉。

请参阅AppDomain.UnhandledExceptionApplication.ThreadException

您可以订阅AppDomain.UnhandledException事件