C# try catch

一、代碼放到try快中(try是c#的關鍵字)。代碼運行是,會嘗試執行try塊內部的語句,若是麼有語句發生異常,這些語句將順序執行下去。直到所有都完成,可是一旦出現異常就跳出try塊,執行catch塊中的內容。二、try塊須要一個或者多個catch塊程序捕捉並處理特定類型的異常。c#

  實驗步驟:首先經過控制檯程序輸入一串字符,使用Console.readLine();獲取一串字符串數據。函數

       而後使用後int.parse(string s);這個函數將字符串轉換爲int型數據。spa

       經過查看int.parse(string s);函數定義能夠知道他又以下異常。code

      

 // 異常:
        //   T:System.ArgumentNullException:
        //     s 爲 null。
        //
        //   T:System.FormatException:
        //     s 的格式不正確。
        //
        //   T:System.OverflowException:
        //     s 表示一個小於 System.Int32.MinValue 或大於 System.Int32.MaxValue 的數字。

      實現代碼:orm

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace tesetData
{
    class Program
    {
       

       
        static void Main(string[] args)
        {
            //try catch的使用 
            string readString = Console.ReadLine();
            int readValue;
            try
            {
                readValue = int.Parse(readString);
                Console.WriteLine(readValue);
            }
            catch (OverflowException)
            {
                Console.WriteLine("err:轉化的不是一個int型數據");
            }
            catch (FormatException)
            {
                Console.WriteLine("err:格式錯誤");
            }
            catch (ArgumentNullException)
            {
                Console.WriteLine("err:null");
            }
            Console.ReadLine();
        }
    }
}

      

 

 

   異常過濾器:blog

  異常過濾器是c# 6的新功能,它影響異常和catch處理程序的匹配方式,容許指定catch除了程序的額外,處理條件。這些條件採用的形式是when關鍵字布爾表達式字符串

  例如:string

catch (OverflowException oe) when (oe.GetType() != typeof(System.FormatException))
{
//處理以前沒有捕捉除了FormatException以外的全部異常
Console.WriteLine("FormatException以外的全部異常");
}

 

 

  

相關文章
相關標籤/搜索