1、代碼放到try快中(try是c#的關鍵字)。代碼運行是,會嘗試執行try塊內部的語句,如果么有語句發生異常,這些語句將順序執行下去。直到全部都完成,但是一旦出現異常就跳出try塊,執行catch塊中的內容。2、try塊需要一個或者多個catch塊程序捕捉並處理特定類型的異常。
實驗步驟:首先通過控制台程序輸入一串字符,使用Console.readLine();獲取一串字符串數據。
然后使用后int.parse(string s);這個函數將字符串轉換為int型數據。
通過查看int.parse(string s);函數定義可以知道他又如下異常。
// 異常: // T:System.ArgumentNullException: // s 為 null。 // // T:System.FormatException: // s 的格式不正確。 // // T:System.OverflowException: // s 表示一個小於 System.Int32.MinValue 或大於 System.Int32.MaxValue 的數字。
實現代碼:
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(); } } }
異常過濾器:
異常過濾器是c# 6的新功能,它影響異常和catch處理程序的匹配方式,允許指定catch除了程序的額外,處理條件。這些條件采用的形式是when關鍵字布爾表達式
例如:
catch (OverflowException oe) when (oe.GetType() != typeof(System.FormatException)) { //處理之前沒有捕捉除了FormatException之外的所有異常 Console.WriteLine("FormatException之外的所有異常"); }