利用自定义的异常处理重起你的应用程序(续)

来源:互联网 发布:光海君 知乎 编辑:程序博客网 时间:2024/05/20 05:07
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

(接上)当加入自定义异常处理类后,通过将下面两行代码加入到主函数中(在Application.Run前面)使它融入到结构中,当第二行将CustomExceptionHandler.OnThreadException附加到TreadException事件时第一行将实例化先前已定义的类,当一个异常没被处理被抛弃后,OnTreadException将被自动调用。

1.           CustomExceptionHandler eh    = new CustomExceptionHandler();

2.           Application.ThreadException += new System.Threading.

3.                                          ThreadExceptionEventHandler(eh.OnThreadException);

 

现在,开始测试,在程序中加入如图的两个按钮,正如你看的,我测试的只是不被处理的异常会引起程序的冲起。

 

 

为“Handled Exception”按钮按键处理加入如下代码:

4.           private void btnHandledException_Click(object sender,

5.                                                  System.EventArgs e)

6.           {

7.             try

8.             {

9.               throw new Exception("Handled Exception");

10.         }

11.         catch (Exception ex)

12.         {

13.           MessageBox.Show(ex.Message);

14.         }

15.       }

为“UnHandled Exception”按钮按键处理加入如下代码:

16.       private void btnUnhandledException_Click(object sender,

17.                                                System.EventArgs e)

18.       {

19.         throw new Exception("Unhandled Exception!!");

20.       }

 

运行应用程序时,当你按” Handled Exception”钮时,只回出现事先设定的消息文本的窗口,按” UnHandled Exception”钮时,将显示结果已写在日志里将重起程序。如图:

click here下载源代码

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>