C# 自訂異常總結及嚴格遵循幾個原則

來源:互聯網
上載者:User

在C#中所有的異常類型都繼承自System.Exception,也就是說,System.Exception是所有異常類的基類. 總起來說,其衍生類別分為兩種:
1. SystemException類: 所有的CLR提供的異常類型都是由SystemException派生。
2. ApplicationException類: 由使用者程式引發,用於派生自訂的異常類型,一般不直接進行執行個體化。

建立自訂異常類應嚴格遵循幾個原則
1. 聲明可序列化(用於進行系列化,當然如果你不需要序列化。那麼可以不聲明為可序列化的)
2. 添加一個預設的建構函式
3. 添加包含message的建構函式
4. 添加一個包含message,及內部異常型別參數的建構函式
5. 添加一個序列化資訊相關參數的建構函式. 複製代碼 代碼如下:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace ConsoleApplication3
{
[Serializable] //聲明為可序列化的 因為要寫入檔案中
public class PayOverflowException : ApplicationException//由使用者程式引發,用於派生自訂的異常類型
{
/// <summary>
/// 預設建構函式
/// </summary>
public PayOverflowException() { }
public PayOverflowException(string message)
: base(message) { }
public PayOverflowException(string message, Exception inner)
: base(message, inner) { }
//public PayOverflowException(System.Runtime.Serialization.SerializationInfo info,
// System.Runtime.Serialization.StreamingContext context)
// : base(info, context) { }
}
internal class Employee
{
public int ID { get; set; }
public string Name { get; set; }
/// <summary>
/// current pay
/// </summary>
public int CurrPay { get; set; }
public Employee() { }
public Employee(int id, string name, int currpay)
{
this.ID = id;
this.Name = name;
this.CurrPay = currpay;
}
/// <summary>
/// 定義一個GiveBunus的虛方法以供不同的衍生類別進行重載
/// </summary>
/// <param name="amount">獎金額度</param>
public virtual void GiveBunus(int amount)
{
//用一個臨時變數記錄遞增之前的值
var pay = CurrPay;
this.CurrPay += amount;
if (CurrPay > 10000)
{
//發生異常,將CurrPay的值進行恢複,
//並拋出異常,外部程式捕獲次異常
this.CurrPay = pay;
var ex = new PayOverflowException("The employee's max pay should be no more than 10000.");
throw ex;
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("**** 建立Employee對象,並用try/catch捕獲異常 *****");
var emp = new Employee(10001, "Yilly", 8000);
try
{
emp.GiveBunus(3000);
}
catch (PayOverflowException ex)
{
Console.WriteLine("異常資訊:{0}\n發生於{1}類的{2}方法", ex.Message,
ex.TargetSite.DeclaringType, ex.TargetSite.Name);
try
{
var file = new FileStream(@"c:\customerexception.txt", FileMode.Create);
//*** 異常資訊寫入檔案中的代碼省略...
//以序列化方式寫入
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(file, ex);
file.Close();
//以位元組方式寫入
//byte[] buffer = System.Text.Encoding.Default.GetBytes(ex.Message);
//int leng = 0;
//leng = buffer.GetLength(0);
//file.Write(buffer, 0, leng);
//file.Close();
}
catch (Exception ex1)
{
var inner = new PayOverflowException(ex.Message, ex1);
throw inner;
}
}
}
}
}

值得注意的是:在執行個體化的時候調用的是PayOverflowException(string message, Exception inner)建構函式,
如果本程式如果有其他程式在調用的時候, 可以通過.InnerExcetpion的Message屬性進行查看內部異常。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.