程序异常错误信息捕获代码

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
namespace CheckedExample
{
 /// <summary>
 /// WebForm1 的摘要说明。
 /// </summary>
 public class Main : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.Button btnCal;
  protected System.Web.UI.WebControls.Label Label2;
  protected System.Web.UI.WebControls.Label lbResult;
  protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
  protected System.Web.UI.WebControls.TextBox tbInput;
  protected System.Web.UI.WebControls.Label Label1;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.btnCal.Click += new System.EventHandler(this.btnCal_Click);
   this.Error += new System.EventHandler(this.WebForm1_Error);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void btnCal_Click(object sender, System.EventArgs e)
  {
   try
   {
    int nInput = int.Parse(tbInput.Text);
    long nResult=1;
    for(int i=1;i<=nInput;i++)
     checked{nResult *= i;}
    lbResult.Text = nResult.ToString();
   }
   catch(OverflowException)//溢出错误异常处理
   {
    throw new Exception("输入的数字太大,我受不了了!");
   }
   catch(FormatException)//输入字符格式错误异常处理
   {
    Response.Write("嘿!要输入整数!");
   }
   catch(Exception ee)
   {
    Response.Write("发生错误,信息为:"+ee.Message);
   }
  
  }

  private void WebForm1_Error(object sender, System.EventArgs e)
  {
   string strMessage = Server.GetLastError().Message;
   //Response.Write(strMessage);
   Server.ClearError();
   //以下把信息写入windows日志
   //要把aspnet用户添加到管理员组中,以便有写注册表权限
   if(!EventLog.SourceExists("mySource"))
    EventLog.CreateEventSource("mySource","myLog");
   EventLog Event = new EventLog();
   Event.Source = "mySource";
   Event.WriteEntry(strMessage,EventLogEntryType.Warning);
   //EventLog.Delete("myLog");
   throw new Exception("我处理不了,请最高人民法院处理!");


  }
 }
}

posted on 2006-11-08 15:43  西湖浪子  阅读(175)  评论(0)    收藏  举报