UnhandledException & ThreadException

When developing a windows/console application using .Net, it is recommended to catch AppDomain.CurrentDomain.UnhandledException and Application.ThreadException. If there are some uncaught exceptions raised in a app-domain, the system default handler will report the exception and terminates the application by default, and if raised in a thread, the thread may be blocked. Catching UnhandledException and ThreadException events provides us a way of creating robust applications.

The following code segements demonstrate how to make use of the two events:

 1  static   void  Main()
 2  {
 3     try  {
 4       //  Setup unhandled exception handlers
 5       //
 6      AppDomain.CurrentDomain.UnhandledException  +=
 7       new  UnhandledExceptionEventHandler(OnUnhandledException);
 8 
 9       //  Unhandled Forms exceptions will be delivered to our ThreadException handler
10       //
11      Application.ThreadException  +=
12       new  System.Threading.ThreadExceptionEventHandler(AppThreadException);
13      dot.gif.
14    }
15     catch ( Exception e ) { dot.gif }
16  }
17 
18  ///   <summary>
19  ///  CLR unhandled exception
20  ///   </summary>
21  private   static   void  OnUnhandledException(Object sender, UnhandledExceptionEventArgs e)
22  {
23    HandleUnhandledException(e.ExceptionObject);
24  }
25 
26  ///   <summary>
27  ///  Displays dialog with information about exceptions that occur in the application.
28  ///   </summary>
29  private   static   void  AppThreadException( object  source, System.Threading.ThreadExceptionEventArgs e)
30  {
31    HandleUnhandledException(e.Exception);
32  }
33 
34  static   void  HandleUnhandledException(Object o)
35  {
36    Exception exp  =  o  as  Exception;
37    MessageBox.Show(exp.Message,  " Application Error " , MessageBoxButtons.OK, MessageBoxIcon.Stop);
38 
39    Application.Exit();  //  Shutting down
40  }
posted on 2005-04-23 09:01  Lin 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/losingmyself/archive/2005/04/23/143715.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值