標籤:程式 for gen 實驗 定義 space image static lin
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# try catch