3

为什么不建议(在最佳实践意义上)从入口点管理系统的所有异常。

class Program
    {
        static void Main(string[] args)
        {
              try
              {
                 [...]//all the program stuff
              }catch(Exception ex)
              {
                    [...]
              }
        }
    }

编辑: 第二点,它是否会改变性能?

4

2 回答 2

5

不建议您在可以实际以有用的方式处理异常的地方捕获异常

如果您对异常无能为力,但崩溃,您的解决方案有效,但请考虑例如丢失的文件给您一个异常。您是否愿意通过“OpenFile”方法中的对话框(或者在这种情况下可能是您打开文件的方法的一部分)来处理它,并可能让用户有机会在继续之前浏览到文件所在的位置,或者会你宁愿把它扔回main,除了“log and crash”之外别无选择?

于 2012-10-05T08:23:19.073 回答
1

这种方法:

  • 不强调在正确的地方捕获预期的异常,即在它们发生的相同上下文中可以处理它们的地方。
  • 不会在另一个线程上捕获异常,因此它不会在多线程环境中工作。
  • 不会捕获许多 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. 
于 2012-10-05T10:52:05.020 回答