To handle Unhandled Exception

 

为了捕捉那些我们没有try{…}catch{…}到的异常(Unhandled Exception),且有一个UI给用户予以友好的提示,我们需要一个机制去处理这些异常。而且,如果我们在任何可能发生异常的地方都使用try{…}catch{…}的话,那将是费力不讨好的事情。

.Net为我们提供了一些机制来处理Unhandled Exception

ASP.Net & Web Services

请看这里的详细内容

 

Windows Forms & Console

MSDN上说使用The UnhandledExceptionEventHandler Delegate,但是我在实际使用中发现它并不好使。

我的代码如下:


        [STAThread]
        
private static void Main(string[] args)
        
{
            
//Error Handle
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Application.Run(
new MainForm());
            
        }

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    
//Show a UI to user… 比如:
    MessageBox.Show(“error …”);
}


此代码在Debug模式下还算幸运(在点击了弹出的MessageBoxOK按钮后,Application结束了),但是在Release模式下根本不起作用——弹出那个令人害怕的JIT Debugging的对话框。对此,我们可以看看CLR Exceptions PM的解释。后来使用了如下代码:
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
    
//
}


 

测试后发现正确捕捉到了那些Unhandled Exception。不过,要注意的是:使用此方法只能捕捉到主线程上发生的异常。

 

Reference

User Friendly Exception Handling

Managing Unhandled Exceptions in .NET

 

posted @ 2005-10-25 15:02  风满袖  阅读(5694)  评论(3编辑  收藏  举报