這個非常簡單只說兩點:1.利用StackFrame來簡化錯誤信息的生成 2.利用自定義異常來簡化信息傳遞.

public class BException : ApplicationException


...{

string _errMsg = "";


public BException() : base() ...{}



public BException(string msg) : base(msg) ...{ this._errMsg = msg; }


public string Message


...{


get ...{ return this._errMsg; }

}


public static BException CreateError(string msg)


...{

StackTrace st = new StackTrace();

StackFrame sf = st.GetFrame(1);

MethoDBase mi = sf.GetMethod();

Type t = mi.DeclaringType;

return new BException(string.Format("Error in {0}::{1} -- {2}",

t.Name, mi.Name, msg));

}

public override string ToString()


...{

return this._errMsg;

}

}
在CreateError方法中利用StackTrace找出調用CreateError的調用者,GetFrame(1).GetFrame(0)就是當前的CreateError方法.是不是很方便. Exception還能簡化函數調用中的消息傳遞.例如我們寫程序經常會有"用戶密碼錯誤","該用戶沒有權限"這樣的消息提示.我們要麼是通過判斷方法的返回值的方式,要麼是通過參數將提示信息返出來.這兩種方式不但麻煩而且調用者還需要記得各個方法返回的涵義.而用Exception是一種較好的方法來解決這個問題把需要提示的信息throw出來,然後統一攔截這個自定義消息進行提示.這裡以ASP.Net來說明統一處理自定義錯誤: 
protected override void OnError(EventArgs e)


...{

BException msg = Server.GetLastError().GetBaseException() as BException;

if(ex != null)


...{

//go(-1)是在提示消息後能夠返回到上一個提交頁面

Response.Write("<script>alert(''"+msg.Message+"'');window.history.go(-1);</script>");

//沒有這句消息提示會有誤

Server.ClearError();


return;

}

}