using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NetTest
{
public class TestException
{
public void TestThrow()
{
//try 塊必須與 catch 或 finally 塊一起使用,並且可以包括多個 catch 塊
try
{
CustomException ex = new CustomException("test custom exception");
ex.ModuleName = "Front-End";
throw ex;
}
/*
多個 catch 塊可以串聯在一起。多個 catch 塊的計算順序是從頂部到底部
但是,對於所引發的每個異常,都只執行一個 catch 塊。
與所引發異常的準確類型或其基類最為匹配的第一個 catch 塊將被執行。
如果沒有任何 catch 塊指定匹配的異常篩選器,則將執行不帶篩選器的 catch 塊(如果有的話)。
需要將帶有最具體的(即派生程度最高的)異常類的 catch 塊放在最前面
*/
catch (CustomException ex)
{
System.Console.Out.WriteLine(ex.Message + "Module is:" + ex.ModuleName);
System.Console.Out.WriteLine("------------------------------");
System.Console.Out.WriteLine(ex.ToString());
}
catch (Exception ex)
{
System.Console.Out.WriteLine(ex.Message);
}
//Finally 塊可讓程式員清理中止的 try 塊可能留下的任何不明確狀態,
//或釋放任何外部資源(形控制代碼、資料庫連接或檔案流)
//而不用等待運行庫中的記憶體回收行程來終結這些對象,finally塊任何情況都執行
finally
{
// Code to execute after try (and possibly catch) here
System.Console.Out.WriteLine("test complete");
}
}
}
//自訂的異常
[Serializable]
class CustomException : Exception
{
public CustomException(string message):base(message)
{
}
public string ModuleName { get; set; }
public override string ToString()
{
return base.ToString() + this.ModuleName.ToString();
}
}
}