这种方法:
- 不强调在正确的地方捕获预期的异常,即在它们发生的相同上下文中可以处理它们的地方。
- 不会在另一个线程上捕获异常,因此它不会在多线程环境中工作。
- 不会捕获许多 Windows 窗体异常,因为它们被 .NET Framework 拦截。
- 吞下所有异常,除非进程损坏。这不是一个好方法,因为当您不理解异常时,您不应该吞下它。
更好的方法是在特定于上下文的方法中捕获预期的异常,在这种方法中,大多数知识都可用于正确处理它们。要捕获意外异常,您的 Main 方法可能如下所示:
// Event handler for handling all UI thread exceptions.
Application.ThreadException +=
new ThreadExceptionEventHandler(App_UiThreadException);
// Force all Windows Forms errors to go through our handler.
// NB In .NET 4, this doesn't apply when the process state is corrupted.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Event handler for handling all non-UI thread exceptions.
AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(App_NonUiThreadException);
// Run the application.