1. 程式人生 > >.net 中的常用異常類

.net 中的常用異常類

1

public class HomeController : Controller
{
    /// <summary>
    /// ContinueWith的使用:
    /// </summary>
    /// <returns></returns>
    public ActionResult Index()
    {
        GetVal(6, 0); //0是不能作為被除數的,所以會引發錯誤
        return View();
    }
    private int Sum(int x, int y)
    {
        return x / y;
    }
    public void GetVal(int x, int y)
    {
        Task<string> t = Task.Run<string>(() => { return Sum(x, y).ToString(); });
        try
        {
            t.Wait();
        }
        catch (AggregateException exs)//表示在應用程式執行期間發生的一個或多個錯誤。
        {
            foreach (var ex in exs.InnerExceptions)
            {
                var errorA = ex.GetBaseException().Message;
                
            }
        }
                        
        //t.ContinueWith(r => { WriteLog("異常資訊:" + t.Exception.GetBaseException().GetType().Name); }, TaskContinuationOptions.OnlyOnFaulted); 
       
    }
    static void WriteLog(string logStr)
    {
        System.IO.File.AppendAllText(@"D:\Log.txt", logStr + "\r\n");
    }
}


說明
基異常型別:
System.Exception 所有異常的基型別。
System.ApplicationException 發生非致命應用程式錯誤時引發的異常。
System.SystemException 為System名稱空間中的預定義異常定義基類。
直接由System.SystemException派生的異常型別:
System.AccessViolationException 在試圖讀寫受保護記憶體時引發的異常。
System.ArgumentException 在向方法提供的其中一個引數無效時引發的異常。
System.Collections.Generic.KeyNotFoundException
指定用於訪問集合中元素的鍵與集合中的任何鍵都不匹配時所引發的異常。
System.IndexOutOfRangeException 訪問陣列時,因元素索引超出陣列邊界而引發的異常。
System.InvalidCastException 因無效型別轉換或顯示轉換引發的異常。
System.InvalidOperationException 當方法呼叫對於物件的當前狀態無效時引發的異常。
System.InvalidProgramException 當程式包含無效Microsoft中間語言(MSIL)或元資料時引發的異常,這通常表示生成程式的編譯器中有bug。
System.IO.IOException
發生I/O錯誤時引發的異常。
System.NotImplementedException 在無法實現請求的方法或操作時引發的異常。
System.NullReferenceException 嘗試對空物件引用進行操作時引發的異常。
System.OutOfMemoryException 沒有足夠的記憶體繼續執行程式時引發的異常。
System.StackOverflowException 掛起的方法呼叫過多而導致執行堆疊溢位時引發的異常。
直接由System.ArgumentException派生的異常型別:
System.ArgumentNullException 當將空引用傳遞給不接受它作為有效引數的方法時引發的異常。
System.ArgumentOutOfRangeException 當引數值超出呼叫的方法所定義的允許取值範圍時引發的異常。
直接由System.ArithmeticException派生的異常型別:
System.DivideByZeroException 試圖用零除整數值或十進位制數值時引發的異常。
System.NotFiniteNumberException 當浮點值為正無窮大、負無窮大或非數字(NaN)時引發的異常。
System.OverflowException 在選中的上下文中所進行的算數運算、型別轉換或轉換操作導致溢位時引發的異常。
直接由System.IOException派生的異常型別:
System.IO.DirectoryNotFoundException 當找不到檔案或目錄的一部分時所引發的異常。
System.IO.DriveNotFoundException 當嘗試訪問的驅動器或共享不可用時引發的異常。
System.IO.EndOfStreamException 讀操作試圖超出流的末尾時引發的異常。
System.IO.FileLoadException 當找到託管程式卻不能載入它時引發的異常。
System.IO.FileNotFoundException 試圖訪問磁碟上不存在的檔案失敗時引發的異常。
System.IO.PathTooLongException 當路徑名或檔名超過系統定義的最大長度時引發的異常。
其他常用異常型別:
ArrayTypeMismatchException 試圖在陣列中儲存錯誤型別的物件。
BadImageFormatException 圖形的格式錯誤。
DivideByZeroException 除零異常。
DllNotFoundException 找不到引用的dll。
FormatException 引數格式錯誤。
MethodAccessException 試圖訪問私有或者受保護的方法。
MissingMemberException 訪問一個無效版本的dll。
NotSupportedException 呼叫的方法在類中沒有實現。
PlatformNotSupportedException 平臺不支援某個特定屬性時丟擲該錯誤。