利用委托机制处理.NET中的异常

利用委托机制处理.NET中的异常<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Terrylee20051210

概述

.NET中,可以轻松的通过try-catch块来捕获异常。为了防止在应用程序中出现未处理的异常,可以通过添加一个全局的异常处理函数,如果是多线程的处理,还必须考虑除了主线程之外的工作线程中的异常处理办法,这里用委托机制来实现。

主线程的异常处理

使用Application对象中的ThreadException属性设置一个delegate来捕获所有的未处理的主线程中出现的异常。注意这个全局异常处理程序,只能捕获到主线程中的异常,对于我们自己添加的工作线程、辅助线程的异常是捕获不到的。

在应用程序入口添加全局异常处理:

 1 ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary>
 2InBlock.gif        /// 应用程序的主入口点。
 3ExpandedBlockEnd.gif        /// </summary>

 4 None.gif         [STAThread]
 5 None.gif         static   void  Main() 
 6 ExpandedBlockStart.gifContractedBlock.gif         dot.gif {    
 7ExpandedSubBlockStart.gifContractedSubBlock.gif            /**////添加主线程的全局异常处理
 8InBlock.gif            Application.ThreadException += new 
 9InBlock.gif                ThreadExceptionEventHandler(
10InBlock.gif                MainUIThreadExceptionHandler);
11InBlock.gif
12InBlock.gif            Application.Run(new Form1());
13ExpandedBlockEnd.gif        }

处理程序:

 1 None.gif public   static   void  MainUIThreadExceptionHandler(Exception ex)
 2 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 3InBlock.gif    MainUIThreadExceptionHandler(nullnew
 4InBlock.gif        ThreadExceptionEventArgs(ex));
 5ExpandedBlockEnd.gif}

 6 None.gif
 7 ExpandedBlockStart.gifContractedBlock.gif /**/ /// <summary>
 8InBlock.gif/// 主线程全局异常信息的处理
 9InBlock.gif/// </summary>
10InBlock.gif/// <param name="sender"></param>
11ExpandedBlockEnd.gif/// <param name="t"></param>

12 None.gif public   static   void  MainUIThreadExceptionHandler( object
13 None.gif    sender, ThreadExceptionEventArgs e)
14 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
15InBlock.gif    MessageBox.Show(
16InBlock.gif        "应用程序发生了如下的异常信息"
17InBlock.gif        + "" + (char)13
18InBlock.gif        + (char)13 + e.Exception.Message
19InBlock.gif        + (char)13 + (char)13
20InBlock.gif        + "请于系统管理员取得联系!"
21InBlock.gif        + (char)13 + (char)13
22InBlock.gif        , "异常信息"
23InBlock.gif        , MessageBoxButtons.OK
24InBlock.gif        , MessageBoxIcon.Error
25InBlock.gif        , MessageBoxDefaultButton.Button1 
26InBlock.gif        , MessageBoxOptions.ServiceNotification);        
27ExpandedBlockEnd.gif}


工作线程的异常处理

编写多线程代码时,我们必须考虑在工作线程中出现的异常。在线程的入口使用try-catch块,并通过delegate将发生的异常通知给主线程。必须将异常信息通知主线程,否则应用程序不会报错,异常将会消失。

在线程入口使用try-catch块:

 1 ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary>
 2InBlock.gif/// 在线程的入口点加入try-catch块
 3ExpandedBlockEnd.gif/// </summary>

 4 None.gif private   void  DataSave()
 5 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 6InBlock.gif    try
 7ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 8InBlock.gif        CreateException();
 9ExpandedSubBlockEnd.gif    }

10InBlock.gif    catch(Exception e)
11ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
12ExpandedSubBlockStart.gifContractedSubBlock.gif        /**////通过delegate转向工作线程的异常处理
13InBlock.gif        new WorkerThreadExceptionHandlerDelegate(
14InBlock.gif            WorkerThreadExceptionHandler).BeginInvoke(e
15InBlock.gif            ,null
16InBlock.gif            ,null);
17ExpandedSubBlockEnd.gif    }

18ExpandedBlockEnd.gif}

工作线程异常的处理:

 1 ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary>
 2InBlock.gif/// 声明工作线程的delegate
 3ExpandedBlockEnd.gif/// </summary>

 4 None.gif public   delegate   void
 5 None.gif    WorkerThreadExceptionHandlerDelegate(Exception e);
 6 None.gif
 7 ExpandedBlockStart.gifContractedBlock.gif /**/ /// <summary>
 8InBlock.gif/// 工作线程的异常处理
 9InBlock.gif/// </summary>
10ExpandedBlockEnd.gif/// <param name="e"></param>

11 None.gif public   void  WorkerThreadExceptionHandler(Exception e)
12 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
13ExpandedSubBlockStart.gifContractedSubBlock.gif    /**////添加其他的处理代码
14InBlock.gif
15ExpandedSubBlockEnd.gif    ///通知全局异常处理程序

16InBlock.gif    MainUIThreadExceptionHandler(
17InBlock.gif        thisnew System.Threading.
18InBlock.gif        ThreadExceptionEventArgs(e));
19ExpandedBlockEnd.gif}

总结

对于捕获到异常,我们可以Log到文件或者数据库,但是必须保证捕获到所有的异常,以上通过委托机制实现了.NET中的主线程以及工作线程中的异常捕获。

完整的程序代码:

  1 None.gif using  System;
  2 None.gif using  System.Drawing;
  3 None.gif using  System.Collections;
  4 None.gif using  System.ComponentModel;
  5 None.gif using  System.Windows.Forms;
  6 None.gif using  System.Data;
  7 None.gif using  System.Threading;
  8 None.gif
  9 None.gif namespace  UseDelegateException
 10 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 11ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
 12InBlock.gif    /// 功能:利用Delegate实现异常的全局处理
 13InBlock.gif    /// 编写:Terrylee
 14InBlock.gif    /// 日期:2005年12月10日
 15ExpandedSubBlockEnd.gif    /// </summary>

 16InBlock.gif    public class Form1 : System.Windows.Forms.Form
 17ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 18InBlock.gif        private System.Windows.Forms.Button btnMainUIThread;
 19InBlock.gif        private System.Windows.Forms.Button btnWorkThread;
 20ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 21InBlock.gif        /// 必需的设计器变量。
 22ExpandedSubBlockEnd.gif        /// </summary>

 23InBlock.gif        private System.ComponentModel.Container components = null;
 24InBlock.gif
 25InBlock.gif        public Form1()
 26ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 27InBlock.gif            //
 28InBlock.gif            // Windows 窗体设计器支持所必需的
 29InBlock.gif            //
 30InBlock.gif            InitializeComponent();
 31InBlock.gif
 32InBlock.gif            //
 33InBlock.gif            // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
 34InBlock.gif            //
 35ExpandedSubBlockEnd.gif        }

 36InBlock.gif
 37ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 38InBlock.gif        /// 清理所有正在使用的资源。
 39ExpandedSubBlockEnd.gif        /// </summary>

 40InBlock.gif        protected override void Dispose( bool disposing )
 41ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 42InBlock.gif            if( disposing )
 43ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 44InBlock.gif                if (components != null
 45ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 46InBlock.gif                    components.Dispose();
 47ExpandedSubBlockEnd.gif                }

 48ExpandedSubBlockEnd.gif            }

 49InBlock.gif            base.Dispose( disposing );
 50ExpandedSubBlockEnd.gif        }

 51InBlock.gif
 52ContractedSubBlock.gifExpandedSubBlockStart.gif        Windows 窗体设计器生成的代码#region Windows 窗体设计器生成的代码
 53ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 54InBlock.gif        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
 55InBlock.gif        /// 此方法的内容。
 56ExpandedSubBlockEnd.gif        /// </summary>

 57InBlock.gif        private void InitializeComponent()
 58ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 59InBlock.gif            this.btnMainUIThread = new System.Windows.Forms.Button();
 60InBlock.gif            this.btnWorkThread = new System.Windows.Forms.Button();
 61InBlock.gif            this.SuspendLayout();
 62InBlock.gif            // 
 63InBlock.gif            // btnMainUIThread
 64InBlock.gif            // 
 65InBlock.gif            this.btnMainUIThread.Location = new System.Drawing.Point(4072);
 66InBlock.gif            this.btnMainUIThread.Name = "btnMainUIThread";
 67InBlock.gif            this.btnMainUIThread.Size = new System.Drawing.Size(11248);
 68InBlock.gif            this.btnMainUIThread.TabIndex = 0;
 69InBlock.gif            this.btnMainUIThread.Text = "主线程异常";
 70InBlock.gif            this.btnMainUIThread.Click += new System.EventHandler(this.btnMainUIThread_Click);
 71InBlock.gif            // 
 72InBlock.gif            // btnWorkThread
 73InBlock.gif            // 
 74InBlock.gif            this.btnWorkThread.Location = new System.Drawing.Point(24072);
 75InBlock.gif            this.btnWorkThread.Name = "btnWorkThread";
 76InBlock.gif            this.btnWorkThread.Size = new System.Drawing.Size(11248);
 77InBlock.gif            this.btnWorkThread.TabIndex = 1;
 78InBlock.gif            this.btnWorkThread.Text = "工作线程异常";
 79InBlock.gif            this.btnWorkThread.Click += new System.EventHandler(this.btnWorkThread_Click);
 80InBlock.gif            // 
 81InBlock.gif            // Form1
 82InBlock.gif            // 
 83InBlock.gif            this.AutoScaleBaseSize = new System.Drawing.Size(614);
 84InBlock.gif            this.ClientSize = new System.Drawing.Size(392197);
 85InBlock.gif            this.Controls.Add(this.btnWorkThread);
 86InBlock.gif            this.Controls.Add(this.btnMainUIThread);
 87InBlock.gif            this.MaximizeBox = false;
 88InBlock.gif            this.Name = "Form1";
 89InBlock.gif            this.Text = "Form1";
 90InBlock.gif            this.ResumeLayout(false);
 91InBlock.gif
 92ExpandedSubBlockEnd.gif        }

 93ExpandedSubBlockEnd.gif        #endregion

 94InBlock.gif
 95ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 96InBlock.gif        /// 应用程序的主入口点。
 97ExpandedSubBlockEnd.gif        /// </summary>

 98InBlock.gif        [STAThread]
 99InBlock.gif        static void Main() 
100ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{    
101ExpandedSubBlockStart.gifContractedSubBlock.gif            /**////添加主线程的全局异常处理
102InBlock.gif            Application.ThreadException += new 
103InBlock.gif                ThreadExceptionEventHandler(
104InBlock.gif                MainUIThreadExceptionHandler);
105InBlock.gif
106InBlock.gif            Application.Run(new Form1());
107ExpandedSubBlockEnd.gif        }

108InBlock.gif        
109InBlock.gif        public static void MainUIThreadExceptionHandler(Exception ex)
110ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
111InBlock.gif            MainUIThreadExceptionHandler(nullnew
112InBlock.gif                ThreadExceptionEventArgs(ex));
113ExpandedSubBlockEnd.gif        }

114InBlock.gif
115ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
116InBlock.gif        /// 主线程全局异常信息的处理
117InBlock.gif        /// </summary>
118InBlock.gif        /// <param name="sender"></param>
119ExpandedSubBlockEnd.gif        /// <param name="t"></param>

120InBlock.gif        public static void MainUIThreadExceptionHandler(object
121InBlock.gif            sender, ThreadExceptionEventArgs e)
122ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
123InBlock.gif            MessageBox.Show(
124InBlock.gif                "应用程序发生了如下的异常信息"
125InBlock.gif                + "" + (char)13
126InBlock.gif                + (char)13 + e.Exception.Message
127InBlock.gif                + (char)13 + (char)13
128InBlock.gif                + "请于系统管理员取得联系!"
129InBlock.gif                + (char)13 + (char)13
130InBlock.gif                , "异常信息"
131InBlock.gif                , MessageBoxButtons.OK
132InBlock.gif                , MessageBoxIcon.Error
133InBlock.gif                , MessageBoxDefaultButton.Button1 
134InBlock.gif                , MessageBoxOptions.ServiceNotification);        
135ExpandedSubBlockEnd.gif        }

136InBlock.gif        
137ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
138InBlock.gif        /// 声明工作线程的delegate
139ExpandedSubBlockEnd.gif        /// </summary>

140InBlock.gif        public delegate void
141InBlock.gif            WorkerThreadExceptionHandlerDelegate(Exception e);
142InBlock.gif
143ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
144InBlock.gif        /// 工作线程的异常处理
145InBlock.gif        /// </summary>
146ExpandedSubBlockEnd.gif        /// <param name="e"></param>

147InBlock.gif        public void WorkerThreadExceptionHandler(Exception e)
148ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
149ExpandedSubBlockStart.gifContractedSubBlock.gif            /**////添加其他的处理代码
150InBlock.gif
151ExpandedSubBlockEnd.gif            ///通知全局异常处理程序

152InBlock.gif            MainUIThreadExceptionHandler(
153InBlock.gif                thisnew System.Threading.
154InBlock.gif                ThreadExceptionEventArgs(e));
155ExpandedSubBlockEnd.gif        }

156ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
157InBlock.gif        /// 制造异常信息,这里抛出一个除0的异常
158ExpandedSubBlockEnd.gif        /// </summary>

159InBlock.gif        private void CreateException()
160ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
161InBlock.gif            int a = 1;
162InBlock.gif            int b = 0;
163InBlock.gif
164InBlock.gif            int c;
165InBlock.gif            c = a/b;
166ExpandedSubBlockEnd.gif        }

167InBlock.gif        
168ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
169InBlock.gif        /// 在线程的入口点加入try-catch块
170ExpandedSubBlockEnd.gif        /// </summary>

171InBlock.gif        private void DataSave()
172ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
173InBlock.gif            try
174ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
175InBlock.gif                CreateException();
176ExpandedSubBlockEnd.gif            }

177InBlock.gif            catch(Exception e)
178ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
179ExpandedSubBlockStart.gifContractedSubBlock.gif                /**////通过delegate转向工作线程的异常处理
180InBlock.gif                new WorkerThreadExceptionHandlerDelegate(
181InBlock.gif                    WorkerThreadExceptionHandler).BeginInvoke(e
182InBlock.gif                    ,null
183InBlock.gif                    ,null);
184ExpandedSubBlockEnd.gif            }

185ExpandedSubBlockEnd.gif        }

186InBlock.gif
187ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
188InBlock.gif        /// 发生主线程异常
189InBlock.gif        /// </summary>
190InBlock.gif        /// <param name="sender"></param>
191ExpandedSubBlockEnd.gif        /// <param name="e"></param>

192InBlock.gif        private void btnMainUIThread_Click(object sender, System.EventArgs e)
193ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
194ExpandedSubBlockStart.gifContractedSubBlock.gif            /**////这里出现一个异常,我们不予捕获,交由全局处理函数
195InBlock.gif            CreateException();
196ExpandedSubBlockEnd.gif        }

197InBlock.gif        
198ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
199InBlock.gif        /// 发生工作线程异常
200InBlock.gif        /// </summary>
201InBlock.gif        /// <param name="sender"></param>
202ExpandedSubBlockEnd.gif        /// <param name="e"></param>

203InBlock.gif        private void btnWorkThread_Click(object sender, System.EventArgs e)
204ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
205InBlock.gif            Thread t = new Thread( new ThreadStart(DataSave));
206InBlock.gif            t.Start();
207ExpandedSubBlockEnd.gif        }

208ExpandedSubBlockEnd.gif    }

209ExpandedBlockEnd.gif}

210 None.gif

转载于:https://www.cnblogs.com/Terrylee/archive/2005/12/12/295243.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值